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

export function useBillableExpenses() {
  const [expenses, setExpenses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { toast } = useToast();

  const fetchExpenses = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: err } = await supabase
        .from('billable_expenses')
        .select('*')
        .order('date', { ascending: false });
      if (err) throw err;
      setExpenses(data || []);
    } catch (err) {
      console.error('Error fetching expenses:', err);
      setError(err.message);
      toast({ variant: "destructive", title: "Error fetching expenses", description: err.message });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const createExpense = async (expenseData) => {
    try {
      const { data, error } = await supabase.from('billable_expenses').insert([expenseData]).select();
      if (error) throw error;
      toast({ title: "Success", description: "Expense created successfully." });
      fetchExpenses();
      return { success: true, data };
    } catch (err) {
      toast({ variant: "destructive", title: "Error", description: err.message });
      return { success: false, error: err };
    }
  };

  const updateExpense = async (id, updates) => {
    try {
      const { data, error } = await supabase.from('billable_expenses').update(updates).eq('id', id).select();
      if (error) throw error;
      toast({ title: "Success", description: "Expense updated successfully." });
      setExpenses(prev => prev.map(e => e.id === id ? { ...e, ...updates } : e));
      return { success: true, data };
    } catch (err) {
      toast({ variant: "destructive", title: "Error", description: err.message });
      return { success: false, error: err };
    }
  };

  const deleteExpense = async (id) => {
    try {
      const { error } = await supabase.from('billable_expenses').delete().eq('id', id);
      if (error) throw error;
      setExpenses(prev => prev.filter(e => e.id !== id));
      toast({ title: "Expense Deleted", description: "Expense has been successfully deleted." });
      return true;
    } catch (err) {
      toast({ variant: "destructive", title: "Error", description: err.message });
      return false;
    }
  };

  const bulkDeleteExpenses = async (ids) => {
    try {
      const { error } = await supabase.from('billable_expenses').delete().in('id', Array.from(ids));
      if (error) throw error;
      setExpenses(prev => prev.filter(e => !ids.has(e.id)));
      toast({ title: "Bulk Delete Successful", description: `Deleted ${ids.size} expenses.` });
      return true;
    } catch (err) {
      toast({ variant: "destructive", title: "Error", description: err.message });
      return false;
    }
  };

  const bulkUpdateStatus = async (ids, status) => {
    try {
      const { error } = await supabase.from('billable_expenses').update({ status }).in('id', Array.from(ids));
      if (error) throw error;
      setExpenses(prev => prev.map(e => ids.has(e.id) ? { ...e, status } : e));
      toast({ title: "Status Updated", description: `Updated status to ${status} for ${ids.size} items.` });
      return true;
    } catch (err) {
      toast({ variant: "destructive", title: "Error", description: err.message });
      return false;
    }
  };

  return {
    expenses,
    loading,
    error,
    fetchExpenses,
    createExpense,
    updateExpense,
    deleteExpense,
    bulkDeleteExpenses,
    bulkUpdateStatus
  };
}
