"use client"

import { useState } from "react"
import { ClipboardList, Plus, X, CheckCircle2, Clock, Trash2 } from "lucide-react"
import { Select } from "@/components/ui/select"
import { formatDate } from "@/lib/utils"
import { toast } from "sonner"

const INSPECTION_TYPES = [
  { value: "move_in",  label: "Move-In"  },
  { value: "move_out", label: "Move-Out" },
  { value: "routine",  label: "Routine"  },
]

const typeColors: Record<string, string> = {
  move_in:  "text-emerald-400 bg-emerald-500/10 border-emerald-500/20",
  move_out: "text-rose-400 bg-rose-500/10 border-rose-500/20",
  routine:  "text-blue-400 bg-blue-500/10 border-blue-500/20",
}

const statusIcon: Record<string, React.ElementType> = {
  draft:    Clock,
  complete: CheckCircle2,
}

export function InspectionManager({ inspections: initial, properties }: { inspections: any[]; properties: any[] }) {
  const [inspections, setInspections] = useState(initial)
  const [showForm, setShowForm] = useState(false)
  const [loading, setLoading] = useState(false)
  const [selectedProp, setSelectedProp] = useState("")
  const [form, setForm] = useState({ type: "move_in", unit_id: "", date: new Date().toISOString().slice(0, 10), notes: "" })

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

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

  const cls = "w-full rounded-lg border border-white/10 bg-white/5 px-3 py-2.5 text-sm text-white placeholder-white/30 outline-none focus:border-indigo-500/50 focus:ring-1 focus:ring-indigo-500 transition"

  async function toggleStatus(id: string, current: string) {
    const next = current === "complete" ? "draft" : "complete"
    const res = await fetch(`/api/inspections/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: next }),
    })
    if (res.ok) {
      setInspections(v => v.map(i => i.id === id ? { ...i, status: next } : i))
      toast.success(next === "complete" ? "Marked complete" : "Marked draft")
    }
  }

  async function deleteInspection(id: string) {
    await fetch(`/api/inspections/${id}`, { method: "DELETE" })
    setInspections(v => v.filter(i => i.id !== id))
    toast.success("Inspection deleted")
  }

  async function create() {
    if (!selectedProp) { toast.error("Select a property"); return }
    setLoading(true)
    const res = await fetch("/api/inspections", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ property_id: selectedProp, ...form }),
    })
    const data = await res.json()
    setLoading(false)
    if (!res.ok) { toast.error(data.error ?? "Failed"); return }
    setInspections(v => [data, ...v])
    setShowForm(false)
    setSelectedProp("")
    setForm({ type: "move_in", unit_id: "", date: new Date().toISOString().slice(0, 10), notes: "" })
    toast.success("Inspection created")
  }

  return (
    <div className="space-y-4">
      {!showForm && (
        <button onClick={() => setShowForm(true)} className="flex items-center gap-2 rounded-xl bg-indigo-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-indigo-500 transition hover:shadow-lg hover:shadow-indigo-500/25">
          <Plus className="h-4 w-4" /> New Inspection
        </button>
      )}

      {showForm && (
        <div className="rounded-2xl border border-indigo-500/20 bg-[#16161f] p-5 space-y-4">
          <div className="flex items-center justify-between">
            <p className="text-sm font-semibold text-white">New Inspection</p>
            <button onClick={() => setShowForm(false)} className="text-white/30 hover:text-white transition"><X className="h-4 w-4" /></button>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-xs text-white/40 mb-1 block">Type</label>
              <Select value={form.type} onChange={v => setForm(f => ({ ...f, type: v }))} options={INSPECTION_TYPES} />
            </div>
            <div>
              <label className="text-xs text-white/40 mb-1 block">Date</label>
              <input type="date" value={form.date} onChange={e => setForm(f => ({ ...f, date: e.target.value }))} className={cls} />
            </div>
          </div>
          <div>
            <label className="text-xs text-white/40 mb-1 block">Property *</label>
            <Select value={selectedProp} onChange={setSelectedProp} options={propertyOptions} />
          </div>
          {selectedProp && (
            <div>
              <label className="text-xs text-white/40 mb-1 block">Unit</label>
              <Select value={form.unit_id} onChange={v => setForm(f => ({ ...f, unit_id: v }))} options={unitOptions} />
            </div>
          )}
          <div>
            <label className="text-xs text-white/40 mb-1 block">Notes</label>
            <input value={form.notes} onChange={e => setForm(f => ({ ...f, notes: e.target.value }))} placeholder="Optional notes…" className={cls} />
          </div>
          <div className="flex gap-3 pt-1">
            <button onClick={() => setShowForm(false)} className="rounded-xl border border-white/10 px-4 py-2 text-sm text-white/40 hover:text-white transition">Cancel</button>
            <button onClick={create} disabled={loading || !selectedProp} className="flex-1 rounded-xl bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-500 disabled:opacity-50 transition">
              {loading ? "Creating…" : "Create Inspection"}
            </button>
          </div>
        </div>
      )}

      {inspections.length === 0 ? (
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] py-14 text-center">
          <ClipboardList className="h-8 w-8 text-white/10 mx-auto mb-3" />
          <p className="text-sm text-white/30">No inspections yet</p>
          <p className="text-xs text-white/20 mt-1">Create move-in and move-out checklists for each unit</p>
        </div>
      ) : (
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="px-5 py-3 border-b border-white/[0.06]">
            <p className="text-sm font-semibold text-white">{inspections.length} Inspection{inspections.length !== 1 ? "s" : ""}</p>
          </div>
          <div className="divide-y divide-white/[0.04]">
            {inspections.map((ins: any) => {
              const StatusIcon = statusIcon[ins.status] ?? Clock
              const typeColor = typeColors[ins.type] ?? typeColors.routine
              const typeLabel = INSPECTION_TYPES.find(t => t.value === ins.type)?.label ?? ins.type
              return (
                <div key={ins.id} className="flex items-center gap-4 px-5 py-4">
                  <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border ${typeColor}`}>
                    <ClipboardList className="h-4 w-4" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="text-sm font-semibold text-white">{typeLabel} Inspection</p>
                      <span className={`rounded-full border px-2 py-0.5 text-[10px] font-medium capitalize ${typeColor}`}>{typeLabel}</span>
                    </div>
                    <p className="text-xs text-white/35 mt-0.5">
                      {ins.property?.name}{ins.unit ? ` · Unit ${ins.unit.unit_number}` : ""} · {formatDate(ins.date)}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => toggleStatus(ins.id, ins.status)}
                      className="flex items-center gap-1 text-xs hover:opacity-80 transition"
                      title={ins.status === "complete" ? "Mark as draft" : "Mark as complete"}
                    >
                      <StatusIcon className={`h-3.5 w-3.5 ${ins.status === "complete" ? "text-emerald-400" : "text-white/30"}`} />
                      <span className="text-white/30 capitalize">{ins.status}</span>
                    </button>
                    <button
                      onClick={() => deleteInspection(ins.id)}
                      className="p-1 text-white/20 hover:text-red-400 hover:bg-red-500/10 rounded-lg transition"
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      )}
    </div>
  )
}
