import { useState, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { getDefaultComplianceTemplate, type ChecklistSection } from "@/data/complianceChecklistTemplate";

export function useComplianceChecklist(associationId: string | undefined) {
  const [sections, setSections] = useState<ChecklistSection[]>([]);
  const [recordId, setRecordId] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const { toast } = useToast();

  const currentYear = new Date().getFullYear();
  const [fiscalYear, setFiscalYear] = useState(currentYear);

  const load = useCallback(async (year?: number) => {
    if (!associationId) return;
    const yr = year ?? fiscalYear;
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from("compliance_checklists")
        .select("*")
        .eq("association_id", associationId)
        .eq("fiscal_year", yr)
        .maybeSingle();
      if (error) throw error;

      if (data) {
        setRecordId(data.id);
        setSections(data.items as unknown as ChecklistSection[]);
      } else {
        setRecordId(null);
        setSections(getDefaultComplianceTemplate());
      }
    } catch (err) {
      console.error(err);
      toast({ variant: "destructive", title: "Error", description: "Failed to load compliance checklist." });
    } finally {
      setLoading(false);
    }
  }, [associationId, fiscalYear, toast]);

  const save = useCallback(async (updatedSections: ChecklistSection[]) => {
    if (!associationId) return;
    setSaving(true);
    try {
      if (recordId) {
        const { error } = await supabase
          .from("compliance_checklists")
          .update({ items: updatedSections as any, updated_at: new Date().toISOString() })
          .eq("id", recordId);
        if (error) throw error;
      } else {
        const { data, error } = await supabase
          .from("compliance_checklists")
          .insert({
            association_id: associationId,
            fiscal_year: fiscalYear,
            items: updatedSections as any,
          })
          .select("id")
          .single();
        if (error) throw error;
        setRecordId(data.id);
      }
    } catch (err) {
      console.error(err);
      toast({ variant: "destructive", title: "Save Failed", description: "Could not save checklist." });
    } finally {
      setSaving(false);
    }
  }, [associationId, fiscalYear, recordId, toast]);

  const toggleItem = useCallback((sectionId: string, categoryId: string, itemId: string) => {
    setSections(prev => {
      const next = prev.map(s => {
        if (s.id !== sectionId) return s;
        return {
          ...s,
          categories: s.categories.map(c => {
            if (c.id !== categoryId) return c;
            return {
              ...c,
              items: c.items.map(i => i.id === itemId ? { ...i, done: !i.done } : i),
            };
          }),
        };
      });
      save(next);
      return next;
    });
  }, [save]);

  const resetChecklist = useCallback(async () => {
    const fresh = getDefaultComplianceTemplate();
    setSections(fresh);
    await save(fresh);
    toast({ title: "Reset", description: "Checklist has been reset to default." });
  }, [save, toast]);

  const addItem = useCallback((sectionId: string, categoryId: string, text: string) => {
    setSections(prev => {
      const next = prev.map(s => {
        if (s.id !== sectionId) return s;
        return {
          ...s,
          categories: s.categories.map(c => {
            if (c.id !== categoryId) return c;
            return {
              ...c,
              items: [...c.items, { id: `custom-${Date.now()}`, text, done: false }],
            };
          }),
        };
      });
      save(next);
      return next;
    });
  }, [save]);

  const removeItem = useCallback((sectionId: string, categoryId: string, itemId: string) => {
    setSections(prev => {
      const next = prev.map(s => {
        if (s.id !== sectionId) return s;
        return {
          ...s,
          categories: s.categories.map(c => {
            if (c.id !== categoryId) return c;
            return { ...c, items: c.items.filter(i => i.id !== itemId) };
          }),
        };
      });
      save(next);
      return next;
    });
  }, [save]);

  const editItem = useCallback((sectionId: string, categoryId: string, itemId: string, newText: string) => {
    setSections(prev => {
      const next = prev.map(s => {
        if (s.id !== sectionId) return s;
        return {
          ...s,
          categories: s.categories.map(c => {
            if (c.id !== categoryId) return c;
            return {
              ...c,
              items: c.items.map(i => i.id === itemId ? { ...i, text: newText } : i),
            };
          }),
        };
      });
      save(next);
      return next;
    });
  }, [save]);

  return {
    sections, loading, saving, fiscalYear, setFiscalYear,
    load, toggleItem, resetChecklist, addItem, removeItem, editItem,
  };
}
