"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Upload, Link as LinkIcon, FileText, Trash2, Loader2, Music, Video, File } from "lucide-react"

export default function MaterialManager({ activity }: { activity: any }) {
  const router = useRouter()
  const [isUploading, setIsUploading] = useState(false)
  const [materialType, setMaterialType] = useState<"file" | "link" | "text">("file")
  
  // Form states
  const [title, setTitle] = useState("")
  const [file, setFile] = useState<File | null>(null)
  const [urlOrText, setUrlOrText] = useState("")

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    console.log("Submitting material...", { title, materialType, file, urlOrText })
    if (!title) return
    if (materialType === "file" && !file) return
    if (materialType !== "file" && !urlOrText) return

    setIsUploading(true)

    try {
      if (materialType === "file" && file) {
        const formData = new FormData()
        formData.append("activityId", activity.id)
        formData.append("title", title)
        formData.append("file", file)

        const res = await fetch("/api/materials", {
          method: "POST",
          body: formData,
        })
        if (!res.ok) throw new Error("Upload failed")
      } else {
        const res = await fetch("/api/materials", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            activityId: activity.id,
            title,
            type: materialType,
            urlOrText
          }),
        })
        if (!res.ok) throw new Error("Adding material failed")
      }

      // Reset form
      setTitle("")
      setFile(null)
      setUrlOrText("")
      router.refresh()
    } catch (err) {
      alert("Failed to add material: " + String(err))
    } finally {
      setIsUploading(false)
    }
  }

  const handleDelete = async (materialId: string) => {
    if (!confirm("Are you sure you want to delete this material?")) return
    try {
      const res = await fetch(`/api/materials/${materialId}`, { method: "DELETE" })
      if (!res.ok) throw new Error("Delete failed")
      router.refresh()
    } catch (err) {
      alert("Failed to delete material")
    }
  }

  const getIcon = (material: any) => {
    if (material.type === "link") return <LinkIcon size={16} />
    if (material.type === "text") return <FileText size={16} />
    
    // Determine file type from extension if possible
    if (material.type === "file") {
      const ext = material.urlOrText.split('.').pop()?.toLowerCase()
      if (['mp3', 'wav', 'm4a', 'ogg'].includes(ext || '')) return <Music size={16} />
      if (['mp4', 'mov', 'webm'].includes(ext || '')) return <Video size={16} />
      return <File size={16} />
    }
  }

  return (
    <div style={{ marginTop: "1rem", borderTop: "1px solid var(--border)", paddingTop: "1rem" }}>
      <h5 style={{ fontWeight: "bold", marginBottom: "0.5rem" }}>Materials ({activity.materials?.length || 0})</h5>
      
      {/* List of existing materials */}
      {activity.materials?.length > 0 && (
        <ul style={{ listStyle: "none", padding: 0, display: "flex", flexDirection: "column", gap: "0.5rem", marginBottom: "1rem" }}>
          {activity.materials.map((m: any) => (
            <li key={m.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", background: "var(--background)", padding: "0.5rem 1rem", borderRadius: "4px", border: "1px solid var(--border)" }}>
              <div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
                <span style={{ color: "var(--primary)", display: "flex" }}>{getIcon(m)}</span>
                <span style={{ fontWeight: "500", fontSize: "0.9rem" }}>{m.title}</span>
              </div>
              <button onClick={() => handleDelete(m.id)} style={{ background: "none", border: "none", color: "var(--destructive, #ef4444)", cursor: "pointer", padding: "4px" }}>
                <Trash2 size={16} />
              </button>
            </li>
          ))}
        </ul>
      )}

      {/* Add new material form */}
      <div style={{ background: "var(--background)", padding: "1rem", borderRadius: "8px", border: "1px solid var(--border)" }}>
        <h6 style={{ fontWeight: "bold", marginBottom: "0.75rem", fontSize: "0.9rem" }}>Add Material</h6>
        <div style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}>
          <button 
            type="button"
            className="btn" 
            style={{ padding: "0.25rem 0.5rem", fontSize: "0.8rem", background: materialType === "file" ? "var(--primary)" : "transparent", color: materialType === "file" ? "white" : "var(--foreground)", border: "1px solid var(--primary)" }}
            onClick={() => setMaterialType("file")}
          ><Upload size={14} style={{ display: "inline", marginRight: "4px" }} /> File</button>
          <button 
            type="button"
            className="btn" 
            style={{ padding: "0.25rem 0.5rem", fontSize: "0.8rem", background: materialType === "link" ? "var(--primary)" : "transparent", color: materialType === "link" ? "white" : "var(--foreground)", border: "1px solid var(--primary)" }}
            onClick={() => setMaterialType("link")}
          ><LinkIcon size={14} style={{ display: "inline", marginRight: "4px" }} /> Link</button>
          <button 
            type="button"
            className="btn" 
            style={{ padding: "0.25rem 0.5rem", fontSize: "0.8rem", background: materialType === "text" ? "var(--primary)" : "transparent", color: materialType === "text" ? "white" : "var(--foreground)", border: "1px solid var(--primary)" }}
            onClick={() => setMaterialType("text")}
          ><FileText size={14} style={{ display: "inline", marginRight: "4px" }} /> Text</button>
        </div>

        <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: "0.5rem" }}>
          <input 
            type="text" 
            placeholder="Title (e.g., 'Let it go - Song')" 
            className="input" 
            value={title} 
            onChange={e => setTitle(e.target.value)} 
            required 
            style={{ padding: "0.5rem", fontSize: "0.9rem" }}
          />

          {materialType === "file" && (
            <input 
              type="file" 
              className="input" 
              onChange={e => setFile(e.target.files?.[0] || null)} 
              required 
              style={{ padding: "0.5rem", fontSize: "0.9rem" }}
              accept="audio/*,video/*,image/*,.pdf,.doc,.docx"
            />
          )}

          {materialType === "link" && (
            <input 
              type="url" 
              placeholder="https://youtube.com/..." 
              className="input" 
              value={urlOrText} 
              onChange={e => setUrlOrText(e.target.value)} 
              required 
              style={{ padding: "0.5rem", fontSize: "0.9rem" }}
            />
          )}

          {materialType === "text" && (
            <textarea 
              placeholder="Paste lyrics, script, or instructions here..." 
              className="input" 
              value={urlOrText} 
              onChange={e => setUrlOrText(e.target.value)} 
              required 
              style={{ padding: "0.5rem", fontSize: "0.9rem", minHeight: "100px" }}
            />
          )}

          <button type="submit" className="btn" disabled={isUploading} style={{ padding: "0.5rem", fontSize: "0.9rem", marginTop: "0.5rem" }}>
            {isUploading ? <><Loader2 size={14} className="spin" style={{ display: "inline", marginRight: "4px" }}/> Saving...</> : "Save Material"}
          </button>
        </form>
      </div>
    </div>
  )
}
