import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useComplianceChecklist } from "@/hooks/useComplianceChecklist";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  Accordion, AccordionContent, AccordionItem, AccordionTrigger,
} from "@/components/ui/accordion";
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { ArrowLeft, Plus, Trash2, RefreshCw, Pencil, Check, X, Loader2 } from "lucide-react";

export default function ComplianceChecklistPage() {
  const { id: associationId } = useParams();
  const navigate = useNavigate();
  const [assocName, setAssocName] = useState("");

  const {
    sections, loading, saving, fiscalYear, setFiscalYear,
    load, toggleItem, resetChecklist, addItem, removeItem, editItem,
  } = useComplianceChecklist(associationId);

  // Load association name
  useEffect(() => {
    if (!associationId) return;
    supabase.from("associations").select("name").eq("id", associationId).single()
      .then(({ data }) => setAssocName(data?.name || ""));
  }, [associationId]);

  // Load checklist on mount / year change
  useEffect(() => { load(fiscalYear); }, [fiscalYear, associationId]);

  // Inline add state
  const [addingTo, setAddingTo] = useState<{ sectionId: string; categoryId: string } | null>(null);
  const [newItemText, setNewItemText] = useState("");

  // Inline edit state
  const [editing, setEditing] = useState<{ itemId: string; text: string } | null>(null);

  const currentYear = new Date().getFullYear();
  const years = Array.from({ length: 5 }, (_, i) => currentYear - 2 + i);

  // Compute totals
  const totalItems = sections.reduce((sum, s) => sum + s.categories.reduce((cs, c) => cs + c.items.length, 0), 0);
  const doneItems = sections.reduce((sum, s) => sum + s.categories.reduce((cs, c) => cs + c.items.filter(i => i.done).length, 0), 0);
  const overallPct = totalItems > 0 ? Math.round((doneItems / totalItems) * 100) : 0;

  if (loading) {
    return (
      <div className="flex items-center justify-center py-24">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-4">
        <div className="flex items-center gap-3">
          <Button variant="ghost" size="icon" onClick={() => navigate(`/dashboard/associations/${associationId}`)}>
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-foreground">Compliance Checklist</h1>
            <p className="text-sm text-muted-foreground">{assocName}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Select value={String(fiscalYear)} onValueChange={(v) => setFiscalYear(Number(v))}>
            <SelectTrigger className="w-[120px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {years.map(y => <SelectItem key={y} value={String(y)}>{y}</SelectItem>)}
            </SelectContent>
          </Select>

          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="outline" size="sm">
                <RefreshCw className="h-4 w-4 mr-1" /> Reset
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Reset Checklist?</AlertDialogTitle>
                <AlertDialogDescription>
                  This will reset all items to unchecked and restore the default template. Custom items will be removed.
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction onClick={resetChecklist}>Reset</AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>

          {saving && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
        </div>
      </div>

      {/* Overall progress */}
      <Card>
        <CardContent className="py-4">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-foreground">Overall Progress — {fiscalYear}</span>
            <span className="text-sm text-muted-foreground">{doneItems}/{totalItems} ({overallPct}%)</span>
          </div>
          <Progress value={overallPct} className="h-3" />
        </CardContent>
      </Card>

      {/* Sections */}
      {sections.map((section) => {
        const sTotal = section.categories.reduce((s, c) => s + c.items.length, 0);
        const sDone = section.categories.reduce((s, c) => s + c.items.filter(i => i.done).length, 0);
        const sPct = sTotal > 0 ? Math.round((sDone / sTotal) * 100) : 0;

        return (
          <Card key={section.id}>
            <CardHeader className="pb-2">
              <div className="flex items-center justify-between">
                <CardTitle className="text-lg">{section.title}</CardTitle>
                <span className="text-sm text-muted-foreground">{sDone}/{sTotal} ({sPct}%)</span>
              </div>
              <Progress value={sPct} className="h-2 mt-1" />
            </CardHeader>
            <CardContent className="pt-0">
              <Accordion type="multiple" defaultValue={section.categories.map(c => c.id)}>
                {section.categories.map((cat) => {
                  const cTotal = cat.items.length;
                  const cDone = cat.items.filter(i => i.done).length;
                  const cPct = cTotal > 0 ? Math.round((cDone / cTotal) * 100) : 0;

                  return (
                    <AccordionItem key={cat.id} value={cat.id}>
                      <AccordionTrigger className="hover:no-underline py-3">
                        <div className="flex items-center gap-2 text-left">
                          <span className="text-lg">{cat.emoji}</span>
                          <span className="font-semibold text-sm">{cat.title}</span>
                          <span className="text-xs text-muted-foreground ml-1">
                            {cDone}/{cTotal}
                          </span>
                          {cPct === 100 && <span className="text-xs text-primary font-medium">✓ Complete</span>}
                        </div>
                      </AccordionTrigger>
                      <AccordionContent>
                        <div className="space-y-1.5 ml-1">
                          {cat.items.map((item) => (
                            <div key={item.id} className="flex items-center gap-2 group">
                              <Checkbox
                                checked={item.done}
                                onCheckedChange={() => toggleItem(section.id, cat.id, item.id)}
                              />
                              {editing?.itemId === item.id ? (
                                <div className="flex items-center gap-1 flex-1">
                                  <Input
                                    value={editing.text}
                                    onChange={(e) => setEditing({ ...editing, text: e.target.value })}
                                    className="h-7 text-sm"
                                    autoFocus
                                    onKeyDown={(e) => {
                                      if (e.key === "Enter") {
                                        editItem(section.id, cat.id, item.id, editing.text);
                                        setEditing(null);
                                      } else if (e.key === "Escape") {
                                        setEditing(null);
                                      }
                                    }}
                                  />
                                  <Button size="icon" variant="ghost" className="h-6 w-6" onClick={() => { editItem(section.id, cat.id, item.id, editing.text); setEditing(null); }}>
                                    <Check className="h-3 w-3" />
                                  </Button>
                                  <Button size="icon" variant="ghost" className="h-6 w-6" onClick={() => setEditing(null)}>
                                    <X className="h-3 w-3" />
                                  </Button>
                                </div>
                              ) : (
                                <>
                                  <span className={`text-sm flex-1 ${item.done ? "line-through text-muted-foreground" : "text-foreground"}`}>
                                    {item.text}
                                  </span>
                                  <div className="opacity-0 group-hover:opacity-100 flex items-center gap-0.5 transition-opacity">
                                    <Button size="icon" variant="ghost" className="h-6 w-6" onClick={() => setEditing({ itemId: item.id, text: item.text })}>
                                      <Pencil className="h-3 w-3" />
                                    </Button>
                                    <Button size="icon" variant="ghost" className="h-6 w-6 text-destructive" onClick={() => removeItem(section.id, cat.id, item.id)}>
                                      <Trash2 className="h-3 w-3" />
                                    </Button>
                                  </div>
                                </>
                              )}
                            </div>
                          ))}

                          {/* Add item */}
                          {addingTo?.sectionId === section.id && addingTo?.categoryId === cat.id ? (
                            <div className="flex items-center gap-1 mt-2">
                              <Input
                                value={newItemText}
                                onChange={(e) => setNewItemText(e.target.value)}
                                placeholder="New item..."
                                className="h-7 text-sm"
                                autoFocus
                                onKeyDown={(e) => {
                                  if (e.key === "Enter" && newItemText.trim()) {
                                    addItem(section.id, cat.id, newItemText.trim());
                                    setNewItemText("");
                                    setAddingTo(null);
                                  } else if (e.key === "Escape") {
                                    setAddingTo(null);
                                    setNewItemText("");
                                  }
                                }}
                              />
                              <Button size="sm" variant="outline" className="h-7" onClick={() => {
                                if (newItemText.trim()) {
                                  addItem(section.id, cat.id, newItemText.trim());
                                  setNewItemText("");
                                }
                                setAddingTo(null);
                              }}>Add</Button>
                              <Button size="sm" variant="ghost" className="h-7" onClick={() => { setAddingTo(null); setNewItemText(""); }}>
                                <X className="h-3 w-3" />
                              </Button>
                            </div>
                          ) : (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="mt-1 text-xs text-muted-foreground h-7"
                              onClick={() => { setAddingTo({ sectionId: section.id, categoryId: cat.id }); setNewItemText(""); }}
                            >
                              <Plus className="h-3 w-3 mr-1" /> Add item
                            </Button>
                          )}
                        </div>
                      </AccordionContent>
                    </AccordionItem>
                  );
                })}
              </Accordion>
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
}
