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

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

  const fetchLedgers = useCallback(async (filters = {}) => {
    setLoading(true);
    try {
      let query = supabase
        .from('owner_ledger_entries')
        .select('*')
        .order('created_at', { ascending: false });

      if (filters.unitId) query = query.eq('unit_id', filters.unitId);
      if (filters.ownerId) query = query.eq('owner_id', filters.ownerId);

      const { data, error: fetchError } = await query;
      if (fetchError) throw fetchError;
      return data;
    } catch (err) {
      setError(err.message);
      toast({ variant: 'destructive', title: 'Error fetching ledgers', description: err.message });
      return [];
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const fetchLedgerById = useCallback(async (id) => {
    setLoading(true);
    try {
      const { data, error: fetchError } = await supabase
        .from('owner_ledger_entries')
        .select('*')
        .eq('id', id)
        .single();
        
      if (fetchError) throw fetchError;
      return data;
    } catch (err) {
      setError(err.message);
      toast({ variant: 'destructive', title: 'Error fetching ledger details', description: err.message });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const createLedger = async (ledgerData) => {
    setLoading(true);
    try {
      const { data, error: insertError } = await supabase
        .from('owner_ledger_entries')
        .insert([ledgerData])
        .select()
        .single();

      if (insertError) throw insertError;
      toast({ title: 'Success', description: 'Ledger entry created successfully.' });
      return data;
    } catch (err) {
      setError(err.message);
      toast({ variant: 'destructive', title: 'Error creating ledger', description: err.message });
      return null;
    } finally {
      setLoading(false);
    }
  };

  const updateLedger = async (id, updateData) => {
    setLoading(true);
    try {
      const { data, error: updateError } = await supabase
        .from('owner_ledger_entries')
        .update({ ...updateData, updated_at: new Date().toISOString() })
        .eq('id', id)
        .select()
        .single();

      if (updateError) throw updateError;
      toast({ title: 'Success', description: 'Ledger entry updated successfully.' });
      return data;
    } catch (err) {
      setError(err.message);
      toast({ variant: 'destructive', title: 'Error updating ledger', description: err.message });
      return null;
    } finally {
      setLoading(false);
    }
  };

  const deleteLedger = async (id) => {
    setLoading(true);
    try {
      const { error: deleteError } = await supabase
        .from('owner_ledger_entries')
        .delete()
        .eq('id', id);

      if (deleteError) throw deleteError;
      toast({ title: 'Success', description: 'Ledger entry deleted successfully.' });
      return true;
    } catch (err) {
      setError(err.message);
      toast({ variant: 'destructive', title: 'Error deleting ledger', description: err.message });
      return false;
    } finally {
      setLoading(false);
    }
  };

  return { loading, error, fetchLedgers, fetchLedgerById, createLedger, updateLedger, deleteLedger };
}
