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

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

  const fetchBills = useCallback(async (statusFilter = null) => {
    setLoading(true);
    try {
      let query = supabase
        .from('bills')
        .select('*')
        .order('created_at', { ascending: false });

      if (statusFilter) {
        query = query.eq('status', statusFilter);
      }

      const { data, error } = await query;
      if (error) throw error;
      setBills(data || []);
    } catch (error) {
      console.error('Error fetching bills:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to load bills." });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const createBill = useCallback(async (billData) => {
    setLoading(true);
    try {
      const { data: userData } = await supabase.auth.getUser();
      const payload = { ...billData, created_by: userData?.user?.id };

      const { data, error } = await supabase
        .from('bills')
        .insert(payload)
        .select()
        .single();
      if (error) throw error;
      toast({ title: "Success", description: "Bill created successfully." });
      return data;
    } catch (error) {
      console.error('Error creating bill:', error);
      toast({ variant: "destructive", title: "Error", description: error.message });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const approveBill = useCallback(async (billId, comment, voterName) => {
    setLoading(true);
    try {
      const { data: userData } = await supabase.auth.getUser();
      const { data: vote, error: approvalError } = await supabase
        .from('bill_approvals')
        .insert({
          bill_id: billId,
          approved_by: userData?.user?.id,
          status: 'approved',
          notes: comment,
          vendor_name: voterName || 'Unknown',
          association_id: (bills.find(b => b.id === billId))?.association_id
        })
        .select()
        .single();
...
        .from('bill_approvals')
        .insert({
          bill_id: billId,
          approved_by: userData?.user?.id,
          status: 'denied',
          notes: comment,
          vendor_name: voterName || 'Unknown',
          association_id: (bills.find(b => b.id === billId))?.association_id
        });
      if (approvalError) throw approvalError;

      const { error: billError } = await supabase
        .from('bills')
        .update({ status: 'denied', updated_at: new Date().toISOString() })
        .eq('id', billId);
      if (billError) throw billError;

      toast({ title: "Voted", description: "Denial vote recorded." });
      setBills(prev => prev.map(b => b.id === billId ? { ...b, status: 'denied' } : b));
      return true;
    } catch (error) {
      console.error('Error denying bill:', error);
      toast({ variant: "destructive", title: "Error", description: error.message });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast, bills]);

  return {
    bills,
    loading,
    fetchBills,
    createBill,
    approveBill,
    denyBill
  };
}
