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

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

  const fetchPaymentPlans = useCallback(async (associationId, isAdmin = false) => {
    setLoading(true);
    setError(null);
    try {
      let query = supabase
        .from('payment_plans')
        .select(`
          *,
          client:clients(name),
          items:payment_plan_items(*)
        `)
        .order('created_at', { ascending: false });

      if (associationId && !isAdmin) {
        query = query.eq('association_id', associationId);
      } else if (associationId && isAdmin) {
         query = query.eq('association_id', associationId);
      }
      
      const { data, error: fetchError } = await query;

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

  const createPaymentPlan = useCallback(async (planData) => {
    setLoading(true);
    try {
      const { data, error: createError } = await supabase
        .from('payment_plans')
        .insert([planData])
        .select()
        .single();

      if (createError) throw createError;
      
      toast({
        title: 'Success',
        description: 'Payment plan created successfully.',
      });
      return data;
    } catch (err) {
      console.error('Error creating payment plan:', err);
      toast({
        variant: 'destructive',
        title: 'Error',
        description: 'Failed to create payment plan.',
      });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const addPaymentItem = useCallback(async (itemData) => {
    setLoading(true);
    try {
      const { data, error: createError } = await supabase
        .from('payment_plan_items')
        .insert([itemData])
        .select()
        .single();

      if (createError) throw createError;

      toast({
        title: 'Success',
        description: 'Payment item added successfully.',
      });
      return data;
    } catch (err) {
      console.error('Error adding payment item:', err);
      toast({
        variant: 'destructive',
        title: 'Error',
        description: 'Failed to add payment item.',
      });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const markPaymentAsReceived = useCallback(async (itemId, receivedDate, receivedBy) => {
    setLoading(true);
    try {
      const { data, error: updateError } = await supabase
        .from('payment_plan_items')
        .update({ 
            received_date: receivedDate,
            received_by: receivedBy
        })
        .eq('id', itemId)
        .select()
        .single();

      if (updateError) throw updateError;

      toast({
        title: 'Success',
        description: 'Payment marked as received.',
      });
      return data;
    } catch (err) {
      console.error('Error updating payment item:', err);
      toast({
        variant: 'destructive',
        title: 'Error',
        description: 'Failed to update payment item.',
      });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const updatePaymentPlanStatus = useCallback(async (planId, status) => {
    setLoading(true);
    try {
      const { data, error: updateError } = await supabase
        .from('payment_plans')
        .update({ status })
        .eq('id', planId)
        .select()
        .single();

      if (updateError) throw updateError;

      toast({
        title: 'Success',
        description: `Payment plan marked as ${status}.`,
      });
      return data;
    } catch (err) {
      console.error('Error updating plan status:', err);
      toast({
        variant: 'destructive',
        title: 'Error',
        description: 'Failed to update plan status.',
      });
      return null;
    } finally {
      setLoading(false);
    }
  }, [toast]);

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

        if (deleteError) throw deleteError;

        toast({
           title: 'Success',
           description: 'Payment plan deleted.',
        });
        return true;
     } catch (err) {
        console.error('Error deleting plan:', err);
        toast({
           variant: 'destructive',
           title: 'Error',
           description: 'Failed to delete payment plan.',
        });
        return false;
     } finally {
        setLoading(false);
     }
  }, [toast]);

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

      if (deleteError) throw deleteError;

      toast({
        title: 'Success',
        description: 'Payment item deleted successfully.',
      });
      return true;
    } catch (err) {
      console.error('Error deleting payment item:', err);
      toast({
        variant: 'destructive',
        title: 'Error',
        description: 'Failed to delete payment item.',
      });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  return {
    loading,
    error,
    fetchPaymentPlans,
    createPaymentPlan,
    addPaymentItem,
    markPaymentAsReceived,
    updatePaymentPlanStatus,
    deletePaymentPlan,
    deletePaymentPlanItem
  };
}
