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

export function useFinancialMetrics() {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const fetchFinancialMetrics = useCallback(async (associationId) => {
    if (!associationId) return [];
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('budgets')
        .select('*')
        .eq('association_id', associationId)
        .order('fiscal_year', { ascending: false });
      if (error) throw error;
      return data || [];
    } catch (error) {
      console.error('Error fetching financial metrics:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to load financial metrics." });
      return [];
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const createFinancialMetrics = useCallback(async (data) => {
    setLoading(true);
    try {
      const { error } = await supabase.from('budgets').insert([data]);
      if (error) throw error;
      toast({ title: "Success", description: "Financial metrics saved successfully." });
      return true;
    } catch (error) {
      console.error('Error creating financial metrics:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to save financial metrics." });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const updateFinancialMetrics = useCallback(async (id, data) => {
    setLoading(true);
    try {
      const { error } = await supabase.from('budgets').update({ ...data, updated_at: new Date().toISOString() }).eq('id', id);
      if (error) throw error;
      toast({ title: "Success", description: "Financial metrics updated successfully." });
      return true;
    } catch (error) {
      console.error('Error updating financial metrics:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to update financial metrics." });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const deleteFinancialMetrics = useCallback(async (id) => {
    setLoading(true);
    try {
      const { error } = await supabase.from('budgets').delete().eq('id', id);
      if (error) throw error;
      toast({ title: "Success", description: "Financial metrics deleted." });
      return true;
    } catch (error) {
      console.error('Error deleting financial metrics:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to delete financial metrics." });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  return { loading, fetchFinancialMetrics, createFinancialMetrics, updateFinancialMetrics, deleteFinancialMetrics };
}
