"use client"

import { useState, useRef } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Select } from "@/components/ui/select"
import { Camera, X, Loader2 } from "lucide-react"

const CATEGORIES = [
  { value: "general",    label: "General"    },
  { value: "plumbing",   label: "Plumbing"   },
  { value: "electrical", label: "Electrical" },
  { value: "hvac",       label: "HVAC"       },
  { value: "appliance",  label: "Appliance"  },
  { value: "structural", label: "Structural" },
  { value: "pest",       label: "Pest"       },
]

const PRIORITIES = [
  { value: "low",       label: "Low"       },
  { value: "medium",    label: "Medium"    },
  { value: "high",      label: "High"      },
  { value: "emergency", label: "Emergency" },
]

export function MaintenanceForm({ properties, tenants, request }: {
  properties: any[]; tenants: any[]; request?: any
}) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [selectedPropertyId, setSelectedPropertyId] = useState(request?.property_id ?? "")
  const [photos, setPhotos] = useState<string[]>(request?.images ?? [])
  const [uploading, setUploading] = useState(false)
  const fileRef = useRef<HTMLInputElement>(null)

  async function handlePhotoUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const files = Array.from(e.target.files ?? [])
    if (!files.length) return
    if (photos.length + files.length > 5) { toast.error("Max 5 photos"); return }

    setUploading(true)

    const uploaded: string[] = []
    for (const file of files) {
      if (file.size > 5 * 1024 * 1024) { toast.error(`${file.name} is too large (max 5MB)`); continue }
      const uploadData = new FormData()
      uploadData.append("file", file)
      uploadData.append("scope", "maintenance")
      const res = await fetch("/api/upload", { method: "POST", body: uploadData })
      if (!res.ok) { toast.error(`Failed to upload ${file.name}`); continue }
      const { url } = await res.json()
      uploaded.push(url)
    }
    setPhotos((prev) => [...prev, ...uploaded])
    setUploading(false)
    if (fileRef.current) fileRef.current.value = ""
  }

  function removePhoto(url: string) {
    setPhotos((prev) => prev.filter((p) => p !== url))
  }

  const propertyOptions = [
    { value: "", label: "Select property…" },
    ...properties.map((p: any) => ({ value: p.id, label: p.name })),
  ]

  const units = properties.find((p: any) => p.id === selectedPropertyId)?.units ?? []
  const unitOptions = [
    { value: "", label: "No specific unit" },
    ...units.map((u: any) => ({ value: u.id, label: `Unit ${u.unit_number}` })),
  ]

  const tenantOptions = [
    { value: "", label: "No tenant" },
    ...tenants.map((t: any) => ({ value: t.id, label: `${t.first_name} ${t.last_name}` })),
  ]

  const cls = "w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white placeholder-white/30 outline-none ring-indigo-500 transition focus:border-indigo-500/50 focus:ring-1"
  const lbl = "mb-1.5 block text-sm font-medium text-white/70"

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setLoading(true)
    setError("")

    const formData = new FormData(e.currentTarget)
    const body = {
      property_id:    formData.get("property_id"),
      unit_id:        formData.get("unit_id") || undefined,
      tenant_id:      formData.get("tenant_id") || undefined,
      title:          formData.get("title"),
      description:    formData.get("description"),
      category:       formData.get("category"),
      priority:       formData.get("priority"),
      assigned_to:    formData.get("assigned_to") || undefined,
      estimated_cost: formData.get("estimated_cost") ? Number(formData.get("estimated_cost")) : undefined,
      images:         photos,
    }

    const res = await fetch(
      request ? `/api/maintenance/${request.id}` : "/api/maintenance",
      { method: request ? "PATCH" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }
    )

    const data = await res.json()
    setLoading(false)

    if (!res.ok) {
      setError(typeof data.error === "string" ? data.error : "Something went wrong")
      return
    }

    toast.success(request ? "Request updated" : "Maintenance request created")
    router.push(`/maintenance/${data.id}`)
    router.refresh()
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5 rounded-xl border border-white/[0.06] bg-[#16161f] p-6">
      {error && (
        <div className="rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</div>
      )}

      <div>
        <label className={lbl}>Title <span className="text-red-400">*</span></label>
        <input name="title" required placeholder="e.g. Leaking faucet in bathroom" defaultValue={request?.title} className={cls} />
      </div>

      <div>
        <label className={lbl}>Description <span className="text-red-400">*</span></label>
        <textarea name="description" required rows={3} placeholder="Describe the issue in detail..." defaultValue={request?.description} className={cls + " resize-none"} />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Category</label>
          <Select name="category" defaultValue={request?.category ?? "general"} options={CATEGORIES} />
        </div>
        <div>
          <label className={lbl}>Priority</label>
          <Select name="priority" defaultValue={request?.priority ?? "medium"} options={PRIORITIES} />
        </div>
      </div>

      <div>
        <label className={lbl}>Property <span className="text-red-400">*</span></label>
        <Select
          name="property_id"
          value={selectedPropertyId}
          onChange={setSelectedPropertyId}
          options={propertyOptions}
          required
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Unit</label>
          <Select name="unit_id" defaultValue={request?.unit_id ?? ""} options={unitOptions} />
        </div>
        <div>
          <label className={lbl}>Reported by Tenant</label>
          <Select name="tenant_id" defaultValue={request?.tenant_id ?? ""} options={tenantOptions} />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={lbl}>Assigned To</label>
          <input name="assigned_to" placeholder="Contractor / vendor name" defaultValue={request?.assigned_to ?? ""} className={cls} />
        </div>
        <div>
          <label className={lbl}>Estimated Cost ($)</label>
          <input name="estimated_cost" type="number" step="0.01" min="0" placeholder="0.00" defaultValue={request?.estimated_cost ?? ""} className={cls} />
        </div>
      </div>

      {/* Photo Upload */}
      <div>
        <label className={lbl}>Photos <span className="text-white/30 font-normal">(up to 5)</span></label>
        <div className="flex flex-wrap gap-2 mb-2">
          {photos.map((url) => (
            <div key={url} className="relative h-20 w-20 overflow-hidden rounded-lg border border-white/10">
              <img src={url} alt="" className="h-full w-full object-cover" />
              <button
                type="button"
                onClick={() => removePhoto(url)}
                className="absolute right-0.5 top-0.5 flex h-5 w-5 items-center justify-center rounded-full bg-black/70 text-white hover:bg-red-500/80 transition"
              >
                <X className="h-3 w-3" />
              </button>
            </div>
          ))}
          {photos.length < 5 && (
            <button
              type="button"
              onClick={() => fileRef.current?.click()}
              disabled={uploading}
              className="flex h-20 w-20 flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed border-white/10 text-white/30 hover:border-indigo-500/40 hover:text-white/50 transition disabled:opacity-50"
            >
              {uploading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Camera className="h-4 w-4" />}
              <span className="text-[10px]">Add</span>
            </button>
          )}
        </div>
        <input ref={fileRef} type="file" accept="image/*" multiple className="hidden" onChange={handlePhotoUpload} />
      </div>

      <div className="flex gap-3 pt-2">
        <button type="button" onClick={() => router.back()} className="rounded-lg border border-white/10 px-5 py-2.5 text-sm text-white/60 hover:text-white transition">
          Cancel
        </button>
        <button type="submit" disabled={loading} className="flex-1 rounded-lg bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-indigo-500 disabled:opacity-50 transition">
          {loading ? "Saving..." : request ? "Save Changes" : "Create Request"}
        </button>
      </div>
    </form>
  )
}
