import React, { useEffect } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/components/ui/use-toast";
import { format, addDays } from "date-fns";

/**
 * Auto Invoice Generator Component
 * Monitors completed events and automatically generates invoices
 * when all staff have ended their shifts
 */
export default function AutoInvoiceGenerator() {
  const { toast } = useToast();
  const queryClient = useQueryClient();

  const { data: events = [] } = useQuery({
    queryKey: ['events-for-invoice-generation'],
    queryFn: () => base44.entities.Event.list(),
    refetchInterval: 60000, // Check every minute
  });

  const { data: invoices = [] } = useQuery({
    queryKey: ['invoices'],
    queryFn: () => base44.entities.Invoice.list(),
  });

  const createInvoiceMutation = useMutation({
    mutationFn: (invoiceData) => base44.entities.Invoice.create(invoiceData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['invoices'] });
    },
  });

  useEffect(() => {
    if (!events || !invoices) return;

    // Find completed events that don't have invoices yet
    const completedEvents = events.filter(event =>
      event.status === "Completed" &&
      !invoices.some(inv => inv.event_id === event.id)
    );

    completedEvents.forEach(async (event) => {
      try {
        // Group staff by role and generate detailed entries
        const roleGroups = {};
        
        if (event.assigned_staff && event.shifts) {
          event.shifts.forEach(shift => {
            shift.roles?.forEach(role => {
              const assignedForRole = event.assigned_staff.filter(
                s => s.role === role.role
              );

              if (!roleGroups[role.role]) {
                roleGroups[role.role] = {
                  role_name: role.role,
                  staff_entries: [],
                  role_subtotal: 0
                };
              }

              assignedForRole.forEach(staff => {
                const workedHours = role.hours || 8;
                const baseRate = role.cost_per_hour || role.rate_per_hour || 0;
                
                // Calculate regular, OT, and DT hours
                const regularHours = Math.min(workedHours, 8);
                const otHours = Math.max(0, Math.min(workedHours - 8, 4));
                const dtHours = Math.max(0, workedHours - 12);
                
                // Calculate rates (OT = 1.5x, DT = 2x)
                const regularRate = baseRate;
                const otRate = baseRate * 1.5;
                const dtRate = baseRate * 2;
                
                // Calculate values
                const regularValue = regularHours * regularRate;
                const otValue = otHours * otRate;
                const dtValue = dtHours * dtRate;
                const total = regularValue + otValue + dtValue;

                const entry = {
                  staff_name: staff.staff_name,
                  staff_id: staff.staff_id,
                  date: event.date,
                  position: role.role,
                  check_in: role.start_time || "09:00 AM",
                  check_out: role.end_time || "05:00 PM",
                  worked_hours: workedHours,
                  regular_hours: regularHours,
                  ot_hours: otHours,
                  dt_hours: dtHours,
                  regular_rate: regularRate,
                  ot_rate: otRate,
                  dt_rate: dtRate,
                  regular_value: regularValue,
                  ot_value: otValue,
                  dt_value: dtValue,
                  rate: baseRate,
                  total: total
                };

                roleGroups[role.role].staff_entries.push(entry);
                roleGroups[role.role].role_subtotal += total;
              });
            });
          });
        }

        const roles = Object.values(roleGroups);
        const subtotal = roles.reduce((sum, role) => sum + role.role_subtotal, 0);
        const otherCharges = 0;
        const total = subtotal + otherCharges;

        // Generate invoice number
        const invoiceNumber = `INV-${Math.floor(Math.random() * 10000)}`;

        // Get vendor and client info
        const vendorInfo = {
          name: event.vendor_name || "Legendary",
          address: "848 E Gish Rd Ste 1, San Jose, CA 95112",
          email: "orders@legendaryeventstaff.com",
          phone: "(408) 936-0180"
        };

        const clientInfo = {
          name: event.business_name || "Client Company",
          address: event.event_location || "Address",
          email: event.client_email || "",
          manager: event.client_name || event.manager_name || "Manager",
          phone: event.client_phone || "",
          vendor_id: "Vendor #"
        };

        // Create invoice
        const invoiceData = {
          invoice_number: invoiceNumber,
          event_id: event.id,
          event_name: event.event_name,
          event_date: event.date,
          po_reference: event.po_reference,
          from_company: vendorInfo,
          to_company: clientInfo,
          business_name: event.business_name,
          manager_name: event.client_name || event.business_name,
          vendor_name: event.vendor_name,
          vendor_id: event.vendor_id,
          hub: event.hub,
          cost_center: event.po_reference,
          roles: roles,
          subtotal: subtotal,
          other_charges: otherCharges,
          amount: total,
          status: "Pending Review",
          issue_date: format(new Date(), 'yyyy-MM-dd'),
          due_date: format(addDays(new Date(), 30), 'yyyy-MM-dd'),
          is_auto_generated: true,
          notes: `Automatically generated invoice for ${event.event_name}`,
        };

        await createInvoiceMutation.mutateAsync(invoiceData);

        toast({
          title: "✅ Invoice Generated",
          description: `Invoice ${invoiceNumber} created for ${event.event_name}`,
        });
      } catch (error) {
        console.error('Failed to generate invoice:', error);
      }
    });
  }, [events, invoices]);

  return null; // This is a background component
}