import { useState } from "react";
import { FileWarning, Download, Printer, Save, Camera, Plus, X, FolderOpen } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { useSavedFormTemplates } from "@/hooks/useSavedFormTemplates";
import LoadTemplateDialog from "@/components/LoadTemplateDialog";

const INCIDENT_TYPES = [
  "Property Damage", "Personal Injury", "Theft", "Vandalism",
  "Water Leak", "Fire", "Slip & Fall", "Vehicle Accident", "Other",
];

export default function IncidentReportForm() {
  const [incidentDate, setIncidentDate] = useState("");
  const [incidentTime, setIncidentTime] = useState("");
  const [incidentType, setIncidentType] = useState("");
  const [location, setLocation] = useState("");
  const [reportedBy, setReportedBy] = useState("");
  const [reporterPhone, setReporterPhone] = useState("");
  const [description, setDescription] = useState("");
  const [actionTaken, setActionTaken] = useState("");
  const [policeReport, setPoliceReport] = useState(false);
  const [policeReportNumber, setPoliceReportNumber] = useState("");
  const [insuranceClaim, setInsuranceClaim] = useState(false);
  const [witnesses, setWitnesses] = useState([]);
  const [photos, setPhotos] = useState([]);

  const addWitness = () => {
    setWitnesses([...witnesses, { id: Date.now(), name: "", phone: "" }]);
  };

  const updateWitness = (id, field, value) => {
    setWitnesses(witnesses.map((w) => (w.id === id ? { ...w, [field]: value } : w)));
  };

  const removeWitness = (id) => {
    setWitnesses(witnesses.filter((w) => w.id !== id));
  };

  const addPhoto = () => {
    setPhotos([...photos, { id: Date.now(), name: `evidence_${photos.length + 1}.jpg` }]);
  };

  const templates = useSavedFormTemplates("incident_report");

  const getFormData = () => ({ incidentDate, incidentTime, incidentType, location, reportedBy, reporterPhone, description, actionTaken, policeReport, policeReportNumber, insuranceClaim, witnesses });
  const applyFormData = (d) => {
    if (d.incidentDate) setIncidentDate(d.incidentDate);
    if (d.incidentTime) setIncidentTime(d.incidentTime);
    if (d.incidentType) setIncidentType(d.incidentType);
    if (d.location !== undefined) setLocation(d.location);
    if (d.reportedBy !== undefined) setReportedBy(d.reportedBy);
    if (d.reporterPhone !== undefined) setReporterPhone(d.reporterPhone);
    if (d.description !== undefined) setDescription(d.description);
    if (d.actionTaken !== undefined) setActionTaken(d.actionTaken);
    if (d.policeReport !== undefined) setPoliceReport(d.policeReport);
    if (d.policeReportNumber !== undefined) setPoliceReportNumber(d.policeReportNumber);
    if (d.insuranceClaim !== undefined) setInsuranceClaim(d.insuranceClaim);
    if (d.witnesses) setWitnesses(d.witnesses);
  };
  const handleSave = () => templates.saveTemplate(`Incident - ${incidentType || incidentDate || "Draft"}`, getFormData());
  const handleLoad = async (id) => { const r = await templates.loadTemplate(id); if (r?.form_data) applyFormData(r.form_data); };
  const handleNew = () => { templates.newTemplate(); setIncidentDate(""); setIncidentTime(""); setIncidentType(""); setLocation(""); setReportedBy(""); setReporterPhone(""); setDescription(""); setActionTaken(""); setPoliceReport(false); setPoliceReportNumber(""); setInsuranceClaim(false); setWitnesses([]); setPhotos([]); };

  return (
    <div className="flex flex-col gap-6 p-6 max-w-4xl">
      <div className="flex items-center gap-3">
        <div className="h-10 w-10 rounded-lg bg-warning/20 flex items-center justify-center">
          <FileWarning className="h-5 w-5 text-warning" />
        </div>
        <div>
          <h2 className="text-lg font-semibold text-foreground">Incident Report</h2>
          <p className="text-sm text-muted-foreground">{templates.currentTemplateId ? `Editing: ${templates.currentTemplateName}` : "New Draft"}</p>
        </div>
        <div className="ml-auto flex gap-1.5">
          <Button variant="outline" size="sm" className="gap-1 text-xs h-8" onClick={handleNew}><Plus className="h-3 w-3" /> New</Button>
          <LoadTemplateDialog templates={templates.savedTemplates} onLoad={handleLoad} onDelete={templates.deleteTemplate} />
          <Button variant="outline" size="sm" className="gap-1 text-xs h-8" onClick={handleSave}><Save className="h-3 w-3" /> Save</Button>
        </div>
      </div>

      <Separator />

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Incident Info */}
        <Card>
          <CardHeader className="pb-3"><CardTitle className="text-sm font-semibold">Incident Information</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs">Date</Label>
                <Input type="date" value={incidentDate} onChange={(e) => setIncidentDate(e.target.value)} className="text-sm" />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Time</Label>
                <Input type="time" value={incidentTime} onChange={(e) => setIncidentTime(e.target.value)} className="text-sm" />
              </div>
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">Incident Type</Label>
              <Select value={incidentType} onValueChange={setIncidentType}>
                <SelectTrigger className="text-sm"><SelectValue placeholder="Select type" /></SelectTrigger>
                <SelectContent>
                  {INCIDENT_TYPES.map((t) => <SelectItem key={t} value={t}>{t}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">Location</Label>
              <Input value={location} onChange={(e) => setLocation(e.target.value)} placeholder="e.g. Pool area, Building B parking lot" className="text-sm" />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">Reported By</Label>
              <Input value={reportedBy} onChange={(e) => setReportedBy(e.target.value)} className="text-sm" />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">Reporter Phone</Label>
              <Input value={reporterPhone} onChange={(e) => setReporterPhone(e.target.value)} className="text-sm" />
            </div>

            <Separator />

            <label className="flex items-center gap-2 text-xs">
              <Checkbox checked={policeReport} onCheckedChange={setPoliceReport} />
              Police report filed
            </label>
            {policeReport && (
              <div className="space-y-1.5">
                <Label className="text-xs">Report Number</Label>
                <Input value={policeReportNumber} onChange={(e) => setPoliceReportNumber(e.target.value)} className="text-sm" />
              </div>
            )}
            <label className="flex items-center gap-2 text-xs">
              <Checkbox checked={insuranceClaim} onCheckedChange={setInsuranceClaim} />
              Insurance claim filed
            </label>
          </CardContent>
        </Card>

        {/* Description & Witnesses */}
        <div className="flex flex-col gap-6">
          <Card>
            <CardHeader className="pb-3"><CardTitle className="text-sm font-semibold">Description</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs">Incident Description</Label>
                <Textarea value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Detailed description of what occurred..." className="text-sm min-h-[100px]" />
              </div>
              <div className="space-y-1.5">
                <Label className="text-xs">Action Taken</Label>
                <Textarea value={actionTaken} onChange={(e) => setActionTaken(e.target.value)} placeholder="What steps were taken in response..." className="text-sm min-h-[60px]" />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-sm font-semibold">Witnesses</CardTitle>
                <Button variant="outline" size="sm" className="gap-1.5 text-xs" onClick={addWitness}>
                  <Plus className="h-3.5 w-3.5" /> Add
                </Button>
              </div>
            </CardHeader>
            <CardContent className="space-y-2">
              {witnesses.length === 0 && <p className="text-[11px] text-muted-foreground">No witnesses added.</p>}
              {witnesses.map((w) => (
                <div key={w.id} className="flex items-center gap-2">
                  <Input value={w.name} onChange={(e) => updateWitness(w.id, "name", e.target.value)} placeholder="Name" className="text-xs h-8 flex-1" />
                  <Input value={w.phone} onChange={(e) => updateWitness(w.id, "phone", e.target.value)} placeholder="Phone" className="text-xs h-8 w-[120px]" />
                  <button onClick={() => removeWitness(w.id)} className="text-destructive/70 hover:text-destructive">
                    <X className="h-3.5 w-3.5" />
                  </button>
                </div>
              ))}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-sm font-semibold">Photo Evidence</CardTitle>
                <Button variant="outline" size="sm" className="gap-1.5 text-xs" onClick={addPhoto}>
                  <Camera className="h-3.5 w-3.5" /> Add Photo
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              {photos.length === 0 ? (
                <p className="text-[11px] text-muted-foreground">No photos attached.</p>
              ) : (
                <div className="flex flex-wrap gap-2">
                  {photos.map((p) => (
                    <Badge key={p.id} variant="secondary" className="gap-1 text-[10px] pr-1">
                      {p.name}
                      <button onClick={() => setPhotos(photos.filter((x) => x.id !== p.id))} className="ml-1 hover:text-destructive"><X className="h-3 w-3" /></button>
                    </Badge>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      <div className="flex items-center gap-2">
        <Button variant="outline" size="sm" className="gap-1.5 text-xs"><Save className="h-3.5 w-3.5" /> Save Draft</Button>
        <Button variant="outline" size="sm" className="gap-1.5 text-xs"><Printer className="h-3.5 w-3.5" /> Print</Button>
        <Button size="sm" className="gap-1.5 text-xs"><Download className="h-3.5 w-3.5" /> Export PDF</Button>
      </div>
    </div>
  );
}
