import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';

export function useExpenseCategories() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchCategories = useCallback(async (associationId) => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: err } = await supabase
        .from('chart_of_accounts')
        .select('*')
        .eq('account_type', 'expense')
        .eq('is_active', true)
        .order('account_name');
      if (err) throw err;
      return data || [];
    } catch (err) {
      console.error('Error fetching expense categories:', err);
      setError(err.message);
      return [];
    } finally {
      setLoading(false);
    }
  }, []);

  const createCategory = async (categoryData) => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: err } = await supabase
        .from('chart_of_accounts')
        .insert([{ ...categoryData, account_type: 'expense' }])
        .select()
        .single();
      if (err) throw err;
      return data;
    } catch (err) {
      console.error('Error creating expense category:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const updateCategory = async (id, updates) => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: err } = await supabase
        .from('chart_of_accounts')
        .update({ ...updates, updated_at: new Date().toISOString() })
        .eq('id', id)
        .select()
        .single();
      if (err) throw err;
      return data;
    } catch (err) {
      console.error('Error updating expense category:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const deleteCategory = async (id) => {
    setLoading(true);
    setError(null);
    try {
      const { error: err } = await supabase.from('chart_of_accounts').delete().eq('id', id);
      if (err) throw err;
      return true;
    } catch (err) {
      console.error('Error deleting expense category:', err);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  return { fetchCategories, createCategory, updateCategory, deleteCategory, loading, error };
}
