import { useState, useEffect, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

/**
 * Hook for saving/loading form templates from the database.
 * @param {string} formType - e.g. "ledger", "agenda", "minutes"
 */
export function useSavedFormTemplates(formType) {
  const [savedTemplates, setSavedTemplates] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentTemplateId, setCurrentTemplateId] = useState(null);
  const [currentTemplateName, setCurrentTemplateName] = useState("");

  const fetchTemplates = useCallback(async () => {
    setLoading(true);
    const { data, error } = await supabase
      .from("saved_form_templates")
      .select("id, name, association_id, updated_at, associations(name)")
      .eq("form_type", formType)
      .order("updated_at", { ascending: false });
    if (error) {
      console.error("Error fetching templates:", error);
    } else {
      setSavedTemplates(data || []);
    }
    setLoading(false);
  }, [formType]);

  useEffect(() => {
    fetchTemplates();
  }, [fetchTemplates]);

  const saveTemplate = useCallback(async (name, formData, associationId = null) => {
    if (!name.trim()) {
      toast.error("Please enter a name before saving");
      return null;
    }

    const { data: { user } } = await supabase.auth.getUser();
    if (!user) {
      toast.error("You must be logged in to save templates");
      return null;
    }

    const payload = {
      user_id: user.id,
      form_type: formType,
      name: name.trim(),
      form_data: formData,
      association_id: associationId || null,
    };

    let result;
    if (currentTemplateId) {
      // Update existing
      const { data, error } = await supabase
        .from("saved_form_templates")
        .update({ name: payload.name, form_data: payload.form_data, association_id: payload.association_id })
        .eq("id", currentTemplateId)
        .select()
        .single();
      if (error) {
        toast.error("Failed to update: " + error.message);
        return null;
      }
      result = data;
      toast.success(`"${name}" updated successfully`);
    } else {
      // Insert new
      const { data, error } = await supabase
        .from("saved_form_templates")
        .insert(payload)
        .select()
        .single();
      if (error) {
        toast.error("Failed to save: " + error.message);
        return null;
      }
      result = data;
      setCurrentTemplateId(data.id);
      toast.success(`"${name}" saved successfully`);
    }

    fetchTemplates();
    return result;
  }, [formType, currentTemplateId, fetchTemplates]);

  const loadTemplate = useCallback(async (templateId) => {
    const { data, error } = await supabase
      .from("saved_form_templates")
      .select("*")
      .eq("id", templateId)
      .single();
    if (error) {
      toast.error("Failed to load template: " + error.message);
      return null;
    }
    setCurrentTemplateId(data.id);
    setCurrentTemplateName(data.name);
    toast.success(`"${data.name}" loaded`);
    return data;
  }, []);

  const deleteTemplate = useCallback(async (templateId) => {
    const { error } = await supabase
      .from("saved_form_templates")
      .delete()
      .eq("id", templateId);
    if (error) {
      toast.error("Failed to delete: " + error.message);
      return false;
    }
    if (currentTemplateId === templateId) {
      setCurrentTemplateId(null);
      setCurrentTemplateName("");
    }
    toast.success("Template deleted");
    fetchTemplates();
    return true;
  }, [currentTemplateId, fetchTemplates]);

  const newTemplate = useCallback(() => {
    setCurrentTemplateId(null);
    setCurrentTemplateName("");
  }, []);

  return {
    savedTemplates,
    loading,
    currentTemplateId,
    currentTemplateName,
    setCurrentTemplateName,
    saveTemplate,
    loadTemplate,
    deleteTemplate,
    newTemplate,
    fetchTemplates,
  };
}
