import { useQuery } from '@tanstack/react-query';
import { supabase } from '@/integrations/supabase/client';
import { addDays, isBefore, isAfter, startOfDay } from 'date-fns';

interface TenancyAlert {
  id: string;
  type: 'inspection' | 'renewal';
  tenancyReference: string;
  propertyAddress: string;
  dueDate: Date;
  daysUntilDue: number;
  tenancyId: string;
}

export const useTenancyAlerts = () => {
  return useQuery({
    queryKey: ['tenancy-alerts'],
    queryFn: async () => {
      const { data: tenancies, error } = await supabase
        .from('tenancies')
        .select(`
          id,
          reference,
          end_date,
          inspection_frequency,
          last_inspection_date,
          start_date,
          status,
          property:properties!tenancies_property_id_fkey(
            display_address,
            address_line_1,
            town_city,
            postcode
          )
        `)
        .is('deleted_at', null)
        .eq('status', 'active');

      if (error) throw error;

      const alerts: TenancyAlert[] = [];
      const today = startOfDay(new Date());
      const in30Days = addDays(today, 30);
      const in60Days = addDays(today, 60);

      tenancies?.forEach(tenancy => {
        const propertyAddress = tenancy.property?.display_address || 
          tenancy.property?.address_line_1 || 
          'Unknown property';

        // Check inspection alerts (30 days before next inspection due)
        if (tenancy.inspection_frequency && tenancy.inspection_frequency > 0) {
          const lastInspection = tenancy.last_inspection_date 
            ? new Date(tenancy.last_inspection_date) 
            : tenancy.start_date 
              ? new Date(tenancy.start_date)
              : null;

          if (lastInspection) {
            const nextInspectionDue = addDays(lastInspection, tenancy.inspection_frequency);
            const alertDate = addDays(nextInspectionDue, -30);

            if (isAfter(alertDate, today) || isBefore(nextInspectionDue, in30Days)) {
              const daysUntilDue = Math.ceil((nextInspectionDue.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
              
              if (daysUntilDue <= 30 && daysUntilDue >= -30) { // Show if within 30 days or up to 30 days overdue
                alerts.push({
                  id: `inspection-${tenancy.id}`,
                  type: 'inspection',
                  tenancyReference: tenancy.reference || 'No reference',
                  propertyAddress,
                  dueDate: nextInspectionDue,
                  daysUntilDue,
                  tenancyId: tenancy.id,
                });
              }
            }
          }
        }

        // Check renewal alerts (60 days before end date)
        if (tenancy.end_date) {
          const endDate = new Date(tenancy.end_date);
          const daysUntilEnd = Math.ceil((endDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));

          if (daysUntilEnd <= 60 && daysUntilEnd >= -30) { // Show if within 60 days or up to 30 days overdue
            alerts.push({
              id: `renewal-${tenancy.id}`,
              type: 'renewal',
              tenancyReference: tenancy.reference || 'No reference',
              propertyAddress,
              dueDate: endDate,
              daysUntilDue: daysUntilEnd,
              tenancyId: tenancy.id,
            });
          }
        }
      });

      // Sort by days until due (most urgent first)
      return alerts.sort((a, b) => a.daysUntilDue - b.daysUntilDue);
    },
    refetchInterval: 5 * 60 * 1000, // Refetch every 5 minutes
  });
};