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

export function usePayables() {
  const [payables, setPayables] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const { toast } = useToast();

  const fetchPayables = useCallback(async (filters = {}, showHistory = false) => {
    setLoading(true);
    setError(null);
    try {
      let query = supabase
        .from('payables')
        .select('*, clients!payables_client_id_fkey(id, name)')
        .order('created_at', { ascending: false });

      let clientId = filters.client_id;
      if (typeof clientId === 'object' && clientId !== null) {
        clientId = clientId.id || clientId.value; 
      }

      if (clientId && clientId !== 'all') {
        query = query.eq('client_id', clientId);
      }

      if (filters.status === 'paid') {
        query = query.eq('is_paid', true);
      } else if (filters.status === 'unpaid') {
        query = query.eq('is_paid', false);
      }

      if (filters.payee) {
        query = query.ilike('payee', `%${filters.payee}%`);
      }

      if (showHistory) {
        if (showHistory === 'only_deleted') {
           query = query.not('deleted_at', 'is', null);
        } else {
           query = query.is('deleted_at', null);
        }
      } else {
        query = query.is('deleted_at', null);
      }

      const { data, error: fetchError } = await query;

      if (fetchError) throw fetchError;
      setPayables(data || []);
    } catch (err) {
      console.error('Error fetching payables:', err);
      setError(err.message);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to load payables data."
      });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const addPayable = async (payableData) => {
    try {
      const cleanData = { ...payableData };
      if (typeof cleanData.client_id === 'object' && cleanData.client_id !== null) {
        cleanData.client_id = cleanData.client_id.id;
      }

      const { error } = await supabase.from('payables').insert([cleanData]);
      if (error) throw error;
      toast({ title: "Success", description: "Payable added successfully." });
      fetchPayables(); 
      return true;
    } catch (error) {
      console.error('Error adding payable:', error);
      toast({ variant: "destructive", title: "Error", description: error.message });
      return false;
    }
  };

  const updatePayable = async (id, updates) => {
    try {
      const cleanUpdates = { ...updates };
      if (typeof cleanUpdates.client_id === 'object' && cleanUpdates.client_id !== null) {
        cleanUpdates.client_id = cleanUpdates.client_id.id;
      }

      const { error } = await supabase.from('payables').update(cleanUpdates).eq('id', id);
      if (error) throw error;
      toast({ title: "Success", description: "Payable updated successfully." });
      fetchPayables();
      return true;
    } catch (error) {
      console.error('Error updating payable:', error);
      toast({ variant: "destructive", title: "Error", description: error.message });
      return false;
    }
  };

  const deletePayable = async (id) => {
    try {
      const { error } = await supabase.from('payables').delete().eq('id', id);
      if (error) throw error;
      toast({ title: "Success", description: "Payable deleted successfully." });
      setPayables(prev => prev.filter(p => p.id !== id));
      return true;
    } catch (error) {
      console.error('Error deleting payable:', error);
      toast({ variant: "destructive", title: "Error", description: error.message });
      return false;
    }
  };

  const markAsPaid = async (payable) => {
    try {
      const newStatus = !payable.is_paid;
      const { error } = await supabase
        .from('payables')
        .update({ is_paid: newStatus })
        .eq('id', payable.id);
      
      if (error) throw error;
      
      setPayables(prev => prev.map(p => 
        p.id === payable.id ? { 
          ...p, 
          is_paid: newStatus,
          marked_paid_date: newStatus ? new Date().toISOString() : null
        } : p
      ));
      
      toast({ title: "Success", description: `Marked as ${newStatus ? 'paid' : 'unpaid'}.` });
    } catch (error) {
      console.error('Error updating status:', error);
      toast({ variant: "destructive", title: "Error", description: error.message });
    }
  };

  const bulkAddPayables = async (payablesList) => {
     try {
      const cleanList = payablesList.map(p => {
        const clean = { ...p };
        if (typeof clean.client_id === 'object' && clean.client_id !== null) {
          clean.client_id = clean.client_id.id;
        }
        return clean;
      });

      const { error } = await supabase.from('payables').insert(cleanList);
      if (error) throw error;
      toast({ title: "Success", description: `${cleanList.length} payables imported.` });
      fetchPayables();
      return true;
    } catch (error) {
      console.error('Error importing payables:', error);
      toast({ variant: "destructive", title: "Error", description: error.message });
      return false;
    }
  };

  return {
    payables,
    loading,
    error,
    fetchPayables,
    addPayable,
    updatePayable,
    deletePayable,
    markAsPaid,
    bulkAddPayables
  };
}
