import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { toast } from 'sonner';

export interface RentPayment {
  id: string;
  tenancy_id: string;
  amount: number;
  due_date: string;
  payment_date: string | null;
  payment_method: string | null;
  reference: string | null;
  status: 'pending' | 'paid' | 'partial' | 'overdue' | 'waived';
  notes: string | null;
  created_at: string;
  updated_at: string;
}

export type RentPaymentInsert = Omit<RentPayment, 'id' | 'created_at' | 'updated_at'>;

export function useRentPayments(tenancyId: string) {
  const queryClient = useQueryClient();

  const paymentsQuery = useQuery({
    queryKey: ['rent-payments', tenancyId],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('rent_payments')
        .select('*')
        .eq('tenancy_id', tenancyId)
        .order('due_date', { ascending: false });

      if (error) throw error;
      return data as RentPayment[];
    },
    enabled: !!tenancyId,
  });

  const createPaymentMutation = useMutation({
    mutationFn: async (payment: Omit<RentPaymentInsert, 'tenancy_id'>) => {
      const { data, error } = await supabase
        .from('rent_payments')
        .insert({
          ...payment,
          tenancy_id: tenancyId,
        })
        .select()
        .single();

      if (error) throw error;
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['rent-payments', tenancyId] });
      toast.success('Payment record added');
    },
    onError: (error) => {
      toast.error('Failed to add payment: ' + error.message);
    },
  });

  const updatePaymentMutation = useMutation({
    mutationFn: async ({ id, ...updates }: Partial<RentPayment> & { id: string }) => {
      const { data, error } = await supabase
        .from('rent_payments')
        .update(updates)
        .eq('id', id)
        .select()
        .single();

      if (error) throw error;
      return data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['rent-payments', tenancyId] });
      toast.success('Payment updated');
    },
    onError: (error) => {
      toast.error('Failed to update payment: ' + error.message);
    },
  });

  const deletePaymentMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase
        .from('rent_payments')
        .delete()
        .eq('id', id);

      if (error) throw error;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['rent-payments', tenancyId] });
      toast.success('Payment deleted');
    },
    onError: (error) => {
      toast.error('Failed to delete payment: ' + error.message);
    },
  });

  // Calculate arrears
  const payments = paymentsQuery.data ?? [];
  const totalDue = payments
    .filter(p => new Date(p.due_date) <= new Date())
    .reduce((sum, p) => sum + Number(p.amount), 0);
  const totalPaid = payments
    .filter(p => p.status === 'paid')
    .reduce((sum, p) => sum + Number(p.amount), 0);
  const arrears = Math.max(0, totalDue - totalPaid);
  const overdueCount = payments.filter(p => p.status === 'overdue').length;

  return {
    payments,
    isLoading: paymentsQuery.isLoading,
    createPayment: createPaymentMutation.mutateAsync,
    updatePayment: updatePaymentMutation.mutateAsync,
    deletePayment: deletePaymentMutation.mutateAsync,
    isCreating: createPaymentMutation.isPending,
    arrears,
    totalDue,
    totalPaid,
    overdueCount,
  };
}
