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

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

export interface AssociationCustomVariableInput {
  association_id: string;
  variable_name: string;
  display_label: string;
  default_value?: string | null;
  description?: string | null;
  category?: string | null;
}

export function useAssociationCustomVariables(associationId?: string) {
  const { toast } = useToast();
  const [variables, setVariables] = useState<AssociationCustomVariable[]>([]);
  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 AssociationCustomVariable[]) || []);
    } catch (err) {
      console.error("Error fetching custom variables:", err);
    } finally {
      setLoading(false);
    }
  }, [associationId]);

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

  const createVariable = async (data: AssociationCustomVariableInput) => {
    const { data: authData, error: authError } = await supabase.auth.getUser();
    if (authError) throw authError;

    const payload = {
      ...data,
      default_value: data.default_value ?? "",
      category: data.category ?? "general",
      created_by: authData.user?.id ?? null,
    };

    const { error } = await supabase.from("custom_variables").insert(payload);
    if (error) throw error;

    await fetchVariables(payload.association_id);
    toast({ title: "Variable created" });
    return payload;
  };

  const updateVariable = async (id: string, updates: Partial<AssociationCustomVariable>) => {
    const targetAssociationId = updates.association_id || associationId;
    const { error } = await supabase
      .from("custom_variables")
      .update(updates)
      .eq("id", id);

    if (error) throw error;

    if (targetAssociationId) {
      await fetchVariables(targetAssociationId);
    }

    toast({ title: "Variable updated" });
    return { id, ...updates };
  };

  const deleteVariable = async (id: string) => {
    const { error } = await supabase.from("custom_variables").delete().eq("id", id);
    if (error) throw error;

    if (associationId) {
      await fetchVariables(associationId);
    } else {
      setVariables((prev) => prev.filter((variable) => variable.id !== id));
    }

    toast({ title: "Variable deleted" });
  };

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