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

export function useBillDetails() {
  const [loading, setLoading] = useState(false);
  const [bill, setBill] = useState(null);
  const [approvals, setApprovals] = useState([]);
  const { toast } = useToast();

  const fetchBillDetail = useCallback(async (id) => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('bills')
        .select('*')
        .eq('id', id)
        .single();
      if (error) throw error;
      setBill(data);

      const { data: approvalsData, error: approvalsError } = await supabase
        .from('bill_approvals')
        .select('*')
        .or(`bill_id.eq.${id},invoice_id.eq.${id}`);
      if (approvalsError) throw approvalsError;
      setApprovals(approvalsData || []);
    } catch (err) {
      console.error('Error fetching bill details:', err);
      toast({ title: "Error", description: "Failed to load bill details.", variant: "destructive" });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const updateBill = async (id, updates) => {
    setLoading(true);
    try {
      const billUpdates = {
        amount: updates.amount,
        due_date: updates.due_date,
        description: updates.notes || updates.description,
        vendor_id: updates.vendor_id
      };

      const { error: billError } = await supabase.from('bills').update(billUpdates).eq('id', id);
      if (billError) throw billError;

      toast({ title: "Success", description: "Bill updated successfully." });
      await fetchBillDetail(id);
      return true;
    } catch (err) {
      console.error('Error updating bill:', err);
      toast({ title: "Error", description: "Failed to update bill.", variant: "destructive" });
      return false;
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    bill,
    approvals,
    fetchBillDetail,
    updateBill
  };
}
