import { useState, useCallback, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";

export interface CustomVariable {
  id: string;
  association_id: string;
  variable_name: string;
  display_label: string;
  default_value: string;
  description: string | null;
  category: string;
  created_by: string | null;
  created_at: string;
  updated_at: string;
}

export function useCustomVariables(associationId?: string) {
  const { toast } = useToast();
  const [variables, setVariables] = useState<CustomVariable[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchVariables = useCallback(async (assocId?: string) => {
    const id = assocId || associationId;
    if (!id) { setVariables([]); return; }

    setLoading(true);
    try {
      const { data, error } = await supabase
        .from("custom_variables")
        .select("*")
        .eq("association_id", id)
        .order("category")
        .order("variable_name");
      if (error) throw error;
      setVariables((data as CustomVariable[]) || []);
    } catch (err: any) {
      console.error("Error fetching custom variables:", err);
    } finally {
      setLoading(false);
    }
  }, [associationId]);

  useEffect(() => {
    if (associationId) fetchVariables(associationId);
  }, [associationId, fetchVariables]);

  const createVariable = async (data: Omit<CustomVariable, "id" | "created_at" | "updated_at" | "created_by">) => {
    const { data: { user } } = await supabase.auth.getUser();
    const payload = { ...data, created_by: user?.id || null };
    console.log("[CustomVariables] Creating variable:", payload);
    const { data: created, error } = await supabase
      .from("custom_variables")
      .insert(payload as any)
      .select()
      .single();
    if (error) {
      console.error("[CustomVariables] Insert error:", error);
      throw error;
    }
    console.log("[CustomVariables] Created:", created);
    setVariables(prev => [...prev, created as CustomVariable].sort((a, b) => a.variable_name.localeCompare(b.variable_name)));
    toast({ title: "Variable created" });
    return created;
  };

  const updateVariable = async (id: string, updates: Partial<CustomVariable>) => {
    const { data: updated, error } = await supabase
      .from("custom_variables")
      .update(updates)
      .eq("id", id)
      .select()
      .single();
    if (error) throw error;
    setVariables(prev => prev.map(v => v.id === id ? (updated as CustomVariable) : v));
    toast({ title: "Variable updated" });
    return updated;
  };

  const deleteVariable = async (id: string) => {
    const { error } = await supabase.from("custom_variables").delete().eq("id", id);
    if (error) throw error;
    setVariables(prev => prev.filter(v => v.id !== id));
    toast({ title: "Variable deleted" });
  };

  return { variables, loading, fetchVariables, createVariable, updateVariable, deleteVariable };
}
