import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ArrowLeft, Plus, Trash2, Clock, Zap } from "lucide-react";
import { createPageUrl } from "@/utils";
import { useToast } from "@/components/ui/use-toast";
import { format, addDays } from "date-fns";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import InvoiceQuickActions from "@/components/invoices/InvoiceQuickActions";

export default function InvoiceEditor() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const urlParams = new URLSearchParams(window.location.search);
  const invoiceId = urlParams.get('id');
  const disputedIndices = urlParams.get('disputed')?.split(',').map(Number).filter(n => !isNaN(n)) || [];
  const isEdit = !!invoiceId;

  const { data: user } = useQuery({
    queryKey: ['current-user-invoice-editor'],
    queryFn: () => base44.auth.me(),
  });

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

  const { data: events = [] } = useQuery({
    queryKey: ['events-for-invoice'],
    queryFn: () => base44.entities.Event.list(),
  });

  const { data: businesses = [] } = useQuery({
    queryKey: ['businesses-for-invoice'],
    queryFn: () => base44.entities.Business.list(),
  });

  const { data: vendorRates = [] } = useQuery({
    queryKey: ['vendor-rates-for-invoice'],
    queryFn: () => base44.entities.VendorRate.list(),
  });

  const { data: staffDirectory = [] } = useQuery({
    queryKey: ['staff-for-invoice'],
    queryFn: () => base44.entities.Staff.list(),
  });

  const { data: allInvoices = [] } = useQuery({
    queryKey: ['all-invoices-for-duplicate'],
    queryFn: () => base44.entities.Invoice.list('-issue_date'),
  });

  const { data: templates = [], refetch: refetchTemplates } = useQuery({
    queryKey: ['invoice-templates'],
    queryFn: () => base44.entities.InvoiceTemplate.list(),
  });

  const existingInvoice = invoices.find(inv => inv.id === invoiceId);
  const [selectedClientId, setSelectedClientId] = useState(existingInvoice?.business_id || "");

  // Generate sequential invoice number based on client prefix
  const generateInvoiceNumber = (clientName, existingInvoices) => {
    // Extract just the main company name (first word, ignore hub/location suffixes)
    const extractCompanyName = (name) => {
      if (!name) return '';
      // Remove common suffixes like "- GPP", "- BVG 300", "Hub", "Campus", etc.
      const cleaned = name.split(/\s*[-–]\s*/)[0].trim();
      return cleaned;
    };

    // Generate prefix from company name
    const generatePrefix = (name) => {
      if (!name) return 'INV';
      const companyName = extractCompanyName(name);
      const words = companyName.trim().split(/\s+/).filter(w => w.length > 0);
      if (words.length === 0) return 'INV';
      if (words.length === 1) {
        // Single word: take first 2-4 letters uppercase
        return words[0].substring(0, 4).toUpperCase();
      } else {
        // Multiple words: take first letter of each word (max 4)
        return words.slice(0, 4).map(w => w[0]).join('').toUpperCase();
      }
    };

    const prefix = generatePrefix(clientName);

    // Find highest existing number for this prefix
    const existingNumbers = (existingInvoices || [])
      .filter(inv => inv.invoice_number?.startsWith(prefix + '-'))
      .map(inv => {
        const match = inv.invoice_number.match(new RegExp(`^${prefix}-(\\d+)$`));
        return match ? parseInt(match[1]) : 0;
      })
      .filter(n => !isNaN(n));

    const nextNumber = existingNumbers.length > 0 ? Math.max(...existingNumbers) + 1 : 1001;
    return `${prefix}-${nextNumber}`;
  };

  const [formData, setFormData] = useState({
    invoice_number: existingInvoice?.invoice_number || generateInvoiceNumber('', allInvoices),
    event_id: existingInvoice?.event_id || "",
    event_name: existingInvoice?.event_name || "",
    invoice_date: existingInvoice?.issue_date || format(new Date(), 'yyyy-MM-dd'),
    due_date: existingInvoice?.due_date || format(addDays(new Date(), 45), 'yyyy-MM-dd'),
    payment_terms: existingInvoice?.payment_terms || "45",
    hub: existingInvoice?.hub || "",
    manager: existingInvoice?.manager_name || "",
    vendor_id: existingInvoice?.vendor_id || "",
    department: existingInvoice?.department || "",
    po_reference: existingInvoice?.po_reference || "",
    from_company: existingInvoice?.from_company || {
      name: "Legendary Event Staffing",
      address: "848 E Gish Rd Ste 1, San Jose, CA 95112",
      phone: "(408) 936-0180",
      email: "order@legendaryeventstaff.com"
    },
    to_company: existingInvoice?.to_company || {
      name: "Thinkloops",
      phone: "4086702861",
      email: "mohsin@thikloops.com",
      address: "Dublin St, San Francisco, CA 94112, USA",
      manager_name: "Manager Name",
      hub_name: "Hub Name",
      vendor_id: "Vendor #"
    },
    staff_entries: existingInvoice?.roles?.[0]?.staff_entries || [],
    charges: existingInvoice?.charges || [],
    other_charges: existingInvoice?.other_charges || 0,
    notes: existingInvoice?.notes || "",
  });

  const [timePickerOpen, setTimePickerOpen] = useState(null);
  const [selectedTime, setSelectedTime] = useState({ hours: "09", minutes: "00", period: "AM" });

  // Get rate for position based on selected client
  const getRateForPosition = (position) => {
    const selectedBusiness = businesses.find(b => b.id === selectedClientId);
    if (!selectedBusiness || !position) return 0;
    
    const businessName = selectedBusiness.business_name || "";
    
    // Extract main company name (e.g., "Google" from "Google - GPP" or "Google - BVG 300")
    const extractCompanyName = (name) => {
      if (!name) return '';
      return name.split(/\s*[-–]\s*/)[0].trim();
    };
    
    const mainCompanyName = extractCompanyName(businessName);
    
    // First priority: Find client-specific rate matching this client
    const clientSpecificRate = vendorRates.find(rate => 
      rate.role_name?.toLowerCase() === position.toLowerCase() &&
      rate.rate_book_type === 'client_specific' &&
      (rate.client_name === businessName || 
       rate.client_name === mainCompanyName ||
       extractCompanyName(rate.client_name) === mainCompanyName)
    );
    
    if (clientSpecificRate) {
      return clientSpecificRate.client_rate || 0;
    }
    
    // Second priority: Find rate matching client's rate_card
    if (selectedBusiness.rate_card) {
      const rateCardMatch = vendorRates.find(rate => 
        rate.role_name?.toLowerCase() === position.toLowerCase() &&
        rate.rate_book_name === selectedBusiness.rate_card
      );
      if (rateCardMatch) {
        return rateCardMatch.client_rate || 0;
      }
    }
    
    // Third priority: Default rate
    const defaultRate = vendorRates.find(rate => 
      rate.role_name?.toLowerCase() === position.toLowerCase() &&
      rate.rate_book_type === 'default'
    );
    
    return defaultRate?.client_rate || 0;
  };

  // Handle client selection
  const handleClientSelect = (clientId) => {
    setSelectedClientId(clientId);
    const selectedBusiness = businesses.find(b => b.id === clientId);
    
    if (selectedBusiness) {
      // Extract hub name from hubs array if available
      const firstHub = selectedBusiness.hubs?.[0];
      const hubName = firstHub?.hub_name || selectedBusiness.hub_building || "";
      
      // Get first department if available
      const firstDepartment = selectedBusiness.departments?.[0] || "";

      // Generate new invoice number with client prefix
      const newInvoiceNumber = generateInvoiceNumber(selectedBusiness.business_name, allInvoices);
      
      setFormData(prev => ({
        ...prev,
        invoice_number: isEdit ? prev.invoice_number : newInvoiceNumber,
        to_company: {
          name: selectedBusiness.business_name || "",
          phone: selectedBusiness.phone || "",
          email: selectedBusiness.email || "",
          address: selectedBusiness.address || (firstHub?.address ? `${firstHub.address}, ${firstHub.city || ''}` : ""),
          manager_name: selectedBusiness.contact_name || "",
          hub_name: hubName,
          vendor_id: selectedBusiness.erp_vendor_id || ""
        },
        hub: hubName,
        manager: selectedBusiness.contact_name || "",
        department: firstDepartment,
        po_reference: selectedBusiness.erp_cost_center || ""
      }));
    }
  };

  // Import from Event - convert event data to invoice entries
  const handleImportFromEvent = (event) => {
    const staffEntries = (event.assigned_staff || []).map(staff => {
      // Find shift info for this staff member
      const shift = event.shifts?.[0];
      const role = shift?.roles?.find(r => r.role === staff.role) || shift?.roles?.[0];
      
      return {
        name: staff.staff_name || "",
        date: event.date ? format(parseISO(event.date), 'MM/dd/yyyy') : format(new Date(), 'MM/dd/yyyy'),
        position: staff.role || role?.role || "",
        check_in: role?.start_time ? convertTo12Hour(role.start_time) : "09:00 AM",
        check_out: role?.end_time ? convertTo12Hour(role.end_time) : "05:00 PM",
        lunch: role?.break_minutes || 30,
        worked_hours: role?.hours || 8,
        regular_hours: Math.min(role?.hours || 8, 8),
        ot_hours: Math.max(0, (role?.hours || 8) - 8),
        dt_hours: 0,
        rate: role?.cost_per_hour || getRateForPosition(staff.role) || 0,
        regular_value: 0,
        ot_value: 0,
        dt_value: 0,
        total: 0
      };
    });

    // Calculate values for each entry
    staffEntries.forEach(entry => {
      entry.regular_value = entry.regular_hours * entry.rate;
      entry.ot_value = entry.ot_hours * entry.rate * 1.5;
      entry.dt_value = entry.dt_hours * entry.rate * 2;
      entry.total = entry.regular_value + entry.ot_value + entry.dt_value;
    });

    // Find the business for this event
    const business = businesses.find(b => b.business_name === event.business_name);

    setFormData(prev => ({
      ...prev,
      event_id: event.id,
      event_name: event.event_name || "",
      hub: event.hub || event.event_location || "",
      manager: event.client_name || "",
      po_reference: event.po_reference || "",
      to_company: business ? {
        name: business.business_name || event.business_name || "",
        phone: business.phone || event.client_phone || "",
        email: business.email || event.client_email || "",
        address: business.address || "",
        manager_name: business.contact_name || event.client_name || "",
        hub_name: event.hub || "",
        vendor_id: business.erp_vendor_id || ""
      } : {
        ...prev.to_company,
        name: event.business_name || prev.to_company.name,
        hub_name: event.hub || ""
      },
      staff_entries: staffEntries.length > 0 ? staffEntries : prev.staff_entries
    }));

    if (business) {
      setSelectedClientId(business.id);
    }

    toast({
      title: "✅ Event Imported",
      description: `Imported ${staffEntries.length} staff entries from ${event.event_name}`,
    });
  };

  // Helper to convert 24h to 12h format
  const convertTo12Hour = (time24) => {
    if (!time24) return "09:00 AM";
    const [hours, minutes] = time24.split(':');
    const hour = parseInt(hours);
    const ampm = hour >= 12 ? 'PM' : 'AM';
    const hour12 = hour % 12 || 12;
    return `${String(hour12).padStart(2, '0')}:${minutes} ${ampm}`;
  };

  // Duplicate Invoice - copy existing invoice with new number and dates
  const handleDuplicateInvoice = (invoice) => {
    const newStaffEntries = (invoice.roles?.[0]?.staff_entries || []).map(entry => ({
      ...entry,
      date: format(new Date(), 'MM/dd/yyyy')
    }));

    // Generate sequential invoice number based on original invoice's client
    const newInvoiceNumber = generateInvoiceNumber(invoice.business_name, allInvoices);

    setFormData({
      invoice_number: newInvoiceNumber,
      event_id: "",
      event_name: invoice.event_name || "",
      invoice_date: format(new Date(), 'yyyy-MM-dd'),
      due_date: format(addDays(new Date(), 45), 'yyyy-MM-dd'),
      payment_terms: invoice.payment_terms || "45",
      hub: invoice.hub || "",
      manager: invoice.manager_name || "",
      vendor_id: invoice.vendor_id || "",
      department: invoice.department || "",
      po_reference: invoice.po_reference || "",
      from_company: invoice.from_company || formData.from_company,
      to_company: invoice.to_company || formData.to_company,
      staff_entries: newStaffEntries,
      charges: invoice.charges || [],
      other_charges: invoice.other_charges || 0,
      notes: invoice.notes || "",
    });

    // Find and set client
    const business = businesses.find(b => b.business_name === invoice.business_name);
    if (business) {
      setSelectedClientId(business.id);
    }

    toast({
      title: "✅ Invoice Duplicated",
      description: `Copied from ${invoice.invoice_number} - update dates and details as needed`,
    });
  };

  // Use Template
  const handleUseTemplate = (template) => {
    const newStaffEntries = (template.staff_entries || []).map(entry => ({
      ...entry,
      name: "",
      date: format(new Date(), 'MM/dd/yyyy'),
      worked_hours: 0,
      regular_hours: 0,
      ot_hours: 0,
      dt_hours: 0,
      regular_value: 0,
      ot_value: 0,
      dt_value: 0,
      total: 0
    }));

    // Generate sequential invoice number based on template's client
    const newInvoiceNumber = generateInvoiceNumber(template.client_name, allInvoices);

    setFormData(prev => ({
      ...prev,
      invoice_number: newInvoiceNumber,
      invoice_date: format(new Date(), 'yyyy-MM-dd'),
      due_date: format(addDays(new Date(), parseInt(template.payment_terms) || 45), 'yyyy-MM-dd'),
      payment_terms: template.payment_terms || "45",
      hub: template.hub || "",
      department: template.department || "",
      po_reference: template.po_reference || "",
      from_company: template.from_company || prev.from_company,
      to_company: template.to_company || prev.to_company,
      staff_entries: newStaffEntries,
      charges: template.charges || [],
      notes: template.notes || "",
    }));

    // Find and set client
    const business = businesses.find(b => b.business_name === template.client_name);
    if (business) {
      setSelectedClientId(business.id);
    }

    toast({
      title: "✅ Template Applied",
      description: `Applied "${template.name}" - fill in staff names and times`,
    });
  };

  // Save as Template
  const handleSaveTemplate = async (templateName) => {
    const templateData = {
      name: templateName,
      client_name: formData.to_company.name,
      from_company: formData.from_company,
      to_company: formData.to_company,
      hub: formData.hub,
      department: formData.department,
      po_reference: formData.po_reference,
      payment_terms: formData.payment_terms,
      staff_entries: formData.staff_entries.map(entry => ({
        position: entry.position,
        rate: entry.rate,
        check_in: entry.check_in,
        check_out: entry.check_out,
        lunch: entry.lunch
      })),
      charges: formData.charges,
      staff_count: formData.staff_entries.length,
      charges_count: formData.charges.length,
      notes: formData.notes,
    };

    await base44.entities.InvoiceTemplate.create(templateData);
    refetchTemplates();

    toast({
      title: "✅ Template Saved",
      description: `"${templateName}" can now be reused for future invoices`,
    });
  };

  // Delete Template
  const handleDeleteTemplate = async (templateId) => {
    await base44.entities.InvoiceTemplate.delete(templateId);
    refetchTemplates();
    toast({
      title: "Template Deleted",
      description: "Template has been removed",
    });
  };

  // Parse ISO date helper
  const parseISO = (dateStr) => {
    if (!dateStr) return new Date();
    return new Date(dateStr);
  };

  // Handle position change with rate auto-fill
  const handlePositionChange = (index, position) => {
    const rate = getRateForPosition(position);
    const newEntries = [...formData.staff_entries];
    newEntries[index] = { 
      ...newEntries[index], 
      position: position,
      rate: rate || newEntries[index].rate 
    };
    
    // Recalculate totals
    const entry = newEntries[index];
    entry.regular_value = (entry.regular_hours || 0) * (entry.rate || 0);
    entry.ot_value = (entry.ot_hours || 0) * (entry.rate || 0) * 1.5;
    entry.dt_value = (entry.dt_hours || 0) * (entry.rate || 0) * 2;
    entry.total = entry.regular_value + entry.ot_value + entry.dt_value;
    
    setFormData({ ...formData, staff_entries: newEntries });
  };

  // Reset time picker when opening
  const openTimePicker = (key) => {
    setSelectedTime({ hours: "09", minutes: "00", period: "AM" });
    setTimePickerOpen(key);
  };

  const sendEmailMutation = useMutation({
        mutationFn: async (invoiceData) => {
          if (!invoiceData.to_company?.email) return { sent: false };

          const emailBody = `
            <h2>Invoice ${invoiceData.invoice_number}</h2>
            <p>Dear ${invoiceData.to_company.name || 'Client'},</p>
            <p>Please find below the invoice details from <strong>${invoiceData.from_company?.name || 'Vendor'}</strong>.</p>
            <hr/>
            <p><strong>Invoice Number:</strong> ${invoiceData.invoice_number}</p>
            <p><strong>Event:</strong> ${invoiceData.event_name || 'N/A'}</p>
            <p><strong>Issue Date:</strong> ${invoiceData.invoice_date}</p>
            <p><strong>Due Date:</strong> ${invoiceData.due_date}</p>
            <p><strong>Amount Due:</strong> $${invoiceData.amount?.toFixed(2) || '0.00'}</p>
            <hr/>
            <p>Please log in to your portal to review and approve this invoice.</p>
            <p>Thank you for your business!</p>
            <p>${invoiceData.from_company?.name || 'Vendor'}<br/>
            ${invoiceData.from_company?.phone || ''}<br/>
            ${invoiceData.from_company?.email || ''}</p>
          `;

          try {
            await base44.integrations.Core.SendEmail({
              to: invoiceData.to_company.email,
              subject: `Invoice ${invoiceData.invoice_number} from ${invoiceData.from_company?.name || 'Vendor'} - Action Required`,
              body: emailBody
            });
            return { sent: true };
          } catch (error) {
            // Email failed (user not in app), but invoice was still saved
            return { sent: false, error: error.message };
          }
        }
      });

      const saveMutation = useMutation({
        mutationFn: async (data) => {
      // Calculate totals
      const staffTotal = data.staff_entries.reduce((sum, entry) => sum + (entry.total || 0), 0);
      const chargesTotal = data.charges.reduce((sum, charge) => sum + ((charge.qty * charge.rate) || 0), 0);
      const subtotal = staffTotal + chargesTotal;
      const total = subtotal + (parseFloat(data.other_charges) || 0);

      const roles = data.staff_entries.length > 0 ? [{
        role_name: "Mixed",
        staff_entries: data.staff_entries,
        role_subtotal: staffTotal
      }] : [];

      const invoiceData = {
        invoice_number: data.invoice_number,
        event_id: data.event_id,
        event_name: data.event_name,
        event_date: data.invoice_date,
        po_reference: data.po_reference,
        from_company: data.from_company,
        to_company: data.to_company,
        business_name: data.to_company.name,
        manager_name: data.manager,
        vendor_name: data.from_company.name,
        vendor_id: data.vendor_id,
        hub: data.hub,
        department: data.department,
        cost_center: data.po_reference,
        roles: roles,
        charges: data.charges,
        subtotal: subtotal,
        other_charges: parseFloat(data.other_charges) || 0,
        amount: total,
        status: existingInvoice?.status === "Disputed" ? "Pending Review" : (existingInvoice?.status || "Draft"),
        dispute_reason: null,
        dispute_details: null,
        disputed_items: null,
        disputed_by: null,
        disputed_date: null,
        issue_date: data.invoice_date,
        due_date: data.due_date,
        payment_terms: data.payment_terms,
        is_auto_generated: false,
        notes: data.notes,
      };

      if (isEdit) {
        return base44.entities.Invoice.update(invoiceId, invoiceData);
      } else {
        return base44.entities.Invoice.create(invoiceData);
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['invoices'] });
      toast({
        title: isEdit ? "✅ Invoice Updated" : "✅ Invoice Created",
        description: isEdit ? "Invoice has been updated successfully" : "Invoice has been created successfully",
      });
      navigate(createPageUrl('Invoices'));
    },
  });

  const handleAddStaffEntry = () => {
    setFormData({
      ...formData,
      staff_entries: [
        ...formData.staff_entries,
        {
          name: "",
          date: format(new Date(), 'MM/dd/yyyy'),
          position: "",
          check_in: "hh:mm",
          lunch: 0,
          check_out: "",
          worked_hours: 0,
          regular_hours: 0,
          ot_hours: 0,
          dt_hours: 0,
          rate: 0,
          regular_value: 0,
          ot_value: 0,
          dt_value: 0,
          total: 0
        }
      ]
    });
  };

  const handleAddCharge = () => {
    setFormData({
      ...formData,
      charges: [
        ...formData.charges,
        {
          name: "Gas Compensation",
          qty: 7.30,
          rate: 0,
          price: 0
        }
      ]
    });
  };

  const parseTimeToMinutes = (timeStr) => {
    if (!timeStr || timeStr === "hh:mm") return null;
    const match = timeStr.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);
    if (!match) return null;
    let hours = parseInt(match[1]);
    const minutes = parseInt(match[2]);
    const period = match[3].toUpperCase();
    if (period === "PM" && hours !== 12) hours += 12;
    if (period === "AM" && hours === 12) hours = 0;
    return hours * 60 + minutes;
  };

  const calculateWorkedHours = (checkIn, checkOut, lunch) => {
    const startMinutes = parseTimeToMinutes(checkIn);
    const endMinutes = parseTimeToMinutes(checkOut);
    if (startMinutes === null || endMinutes === null) return 0;
    let totalMinutes = endMinutes - startMinutes;
    if (totalMinutes < 0) totalMinutes += 24 * 60; // Handle overnight shifts
    
    // Break rules for employee pay:
    // NB (No Break) - no deduction
    // 5, 10, 15 min - paid breaks, no deduction
    // 20+ min - unpaid breaks, deduct from worked hours
    if (lunch !== "NB" && lunch >= 20) {
      totalMinutes -= lunch; // Only subtract if 20+ min break
    }
    return Math.max(0, totalMinutes / 60);
  };

  const calculateBillableHours = (checkIn, checkOut, lunch) => {
    const startMinutes = parseTimeToMinutes(checkIn);
    const endMinutes = parseTimeToMinutes(checkOut);
    if (startMinutes === null || endMinutes === null) return { total: 0, nbPenalty: 0 };
    let totalMinutes = endMinutes - startMinutes;
    if (totalMinutes < 0) totalMinutes += 24 * 60; // Handle overnight shifts
    
    // Billing rules for client:
    // NB (No Break) - add 1 extra REGULAR hour (not OT)
    // 5, 10, 15 min - paid breaks, client pays for these
    // 20+ min - unpaid breaks, deduct from billable hours
    let nbPenalty = 0;
    if (lunch === "NB") {
      nbPenalty = 1; // 1 extra regular hour penalty
    } else if (lunch >= 20) {
      totalMinutes -= lunch; // Only subtract if 20+ min break
    }
    // For 5, 10, 15 min breaks - no deduction, client pays full time
    return { total: Math.max(0, totalMinutes / 60), nbPenalty };
  };

  const handleStaffChange = (index, field, value) => {
    const newEntries = [...formData.staff_entries];
    newEntries[index] = { ...newEntries[index], [field]: value };
    
    const entry = newEntries[index];
    
    // Auto-calculate worked hours when check-in, check-out, or lunch changes
    if (['check_in', 'check_out', 'lunch'].includes(field)) {
      const workedHours = calculateWorkedHours(entry.check_in, entry.check_out, entry.lunch);
      const { total: billableHours, nbPenalty } = calculateBillableHours(entry.check_in, entry.check_out, entry.lunch);
      entry.worked_hours = parseFloat(workedHours.toFixed(2));
      
      // Distribute billable hours: first 8 regular, next 4 OT (1.5x), rest DT (2x)
      if (billableHours <= 8) {
        entry.regular_hours = parseFloat(billableHours.toFixed(2));
        entry.ot_hours = 0;
        entry.dt_hours = 0;
      } else if (billableHours <= 12) {
        entry.regular_hours = 8;
        entry.ot_hours = parseFloat((billableHours - 8).toFixed(2));
        entry.dt_hours = 0;
      } else {
        entry.regular_hours = 8;
        entry.ot_hours = 4;
        entry.dt_hours = parseFloat((billableHours - 12).toFixed(2));
      }
      
      // NB (No Break) penalty: add 1 extra REGULAR hour (not OT)
      if (nbPenalty > 0) {
        entry.regular_hours = parseFloat((entry.regular_hours + nbPenalty).toFixed(2));
      }
    }
    
    // Recalculate totals if time-related fields change
    if (['check_in', 'check_out', 'lunch', 'worked_hours', 'regular_hours', 'ot_hours', 'dt_hours', 'rate'].includes(field)) {
      entry.regular_value = (entry.regular_hours || 0) * (entry.rate || 0);
      entry.ot_value = (entry.ot_hours || 0) * (entry.rate || 0) * 1.5;
      entry.dt_value = (entry.dt_hours || 0) * (entry.rate || 0) * 2;
      entry.total = entry.regular_value + entry.ot_value + entry.dt_value;
    }
    
    setFormData({ ...formData, staff_entries: newEntries });
  };

  const handleChargeChange = (index, field, value) => {
    const newCharges = [...formData.charges];
    newCharges[index] = { ...newCharges[index], [field]: value };
    
    if (['qty', 'rate'].includes(field)) {
      newCharges[index].price = (newCharges[index].qty || 0) * (newCharges[index].rate || 0);
    }
    
    setFormData({ ...formData, charges: newCharges });
  };

  const handleRemoveStaff = (index) => {
    setFormData({
      ...formData,
      staff_entries: formData.staff_entries.filter((_, i) => i !== index)
    });
  };

  const handleRemoveCharge = (index) => {
    setFormData({
      ...formData,
      charges: formData.charges.filter((_, i) => i !== index)
    });
  };

  const handleTimeSelect = (entryIndex, field) => {
    const timeString = `${selectedTime.hours}:${selectedTime.minutes} ${selectedTime.period}`;
    handleStaffChange(entryIndex, field, timeString);
    setTimePickerOpen(null);
  };

  const calculateTotals = () => {
    const staffTotal = formData.staff_entries.reduce((sum, entry) => sum + (entry.total || 0), 0);
    const chargesTotal = formData.charges.reduce((sum, charge) => sum + (charge.price || 0), 0);
    const subtotal = staffTotal + chargesTotal;
    const otherCharges = parseFloat(formData.other_charges) || 0;
    const grandTotal = subtotal + otherCharges;
    
    return { subtotal, otherCharges, grandTotal };
  };

  const totals = calculateTotals();

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-slate-50 p-6">
      <div className="max-w-7xl mx-auto">
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Button variant="outline" onClick={() => navigate(createPageUrl('Invoices'))} className="bg-white">
              <ArrowLeft className="w-4 h-4 mr-2" />
              Back to Invoices
            </Button>
            <div>
              <h1 className="text-2xl font-bold text-slate-900">{isEdit ? 'Edit Invoice' : 'Create New Invoice'}</h1>
              <p className="text-sm text-slate-600">Complete all invoice details below</p>
            </div>
          </div>
          <Badge className="bg-blue-100 text-blue-700 text-sm px-3 py-1">
            {existingInvoice?.status || "Draft"}
          </Badge>
        </div>

        {/* Dispute Alert Banner */}
        {existingInvoice?.status === "Disputed" && disputedIndices.length > 0 && (
          <div className="bg-red-50 border-2 border-red-300 rounded-xl p-4 mb-6">
            <div className="flex items-start gap-3">
              <div className="w-8 h-8 bg-red-500 rounded-full flex items-center justify-center flex-shrink-0">
                <span className="text-white font-bold">!</span>
              </div>
              <div>
                <h3 className="font-bold text-red-800">Disputed Items Highlighted</h3>
                <p className="text-sm text-red-700 mt-1">
                  {disputedIndices.length} line item(s) have been disputed by the client. 
                  <strong> Reason: </strong>{existingInvoice.dispute_reason || "Not specified"}
                </p>
                {existingInvoice.dispute_details && (
                  <p className="text-sm text-red-600 mt-2 bg-white p-2 rounded border border-red-200">
                    "{existingInvoice.dispute_details}"
                  </p>
                )}
                <p className="text-xs text-red-600 mt-2">
                  Please review and correct the highlighted rows, then resubmit for approval.
                </p>
              </div>
            </div>
          </div>
        )}

        <Card className="p-8 bg-white shadow-lg border-blue-100">
          {/* Quick Actions - Only for new invoices */}
          {!isEdit && (
            <InvoiceQuickActions
              events={events}
              invoices={allInvoices}
              templates={templates}
              onImportFromEvent={handleImportFromEvent}
              onDuplicateInvoice={handleDuplicateInvoice}
              onUseTemplate={handleUseTemplate}
              onSaveTemplate={handleSaveTemplate}
              onDeleteTemplate={handleDeleteTemplate}
            />
          )}

          {/* Client Selection - Top Section */}
          {!isEdit && (
            <div className="mb-6 p-4 bg-gradient-to-r from-emerald-50 to-green-100 rounded-xl border-2 border-emerald-200">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 bg-emerald-600 rounded-lg flex items-center justify-center">
                  <span className="text-white font-bold">🏢</span>
                </div>
                <div>
                  <h3 className="font-bold text-emerald-900">Select Client</h3>
                  <p className="text-xs text-emerald-700">Choose a client to auto-fill company details and rates</p>
                </div>
              </div>
              <Select value={selectedClientId} onValueChange={handleClientSelect}>
                <SelectTrigger className="bg-white border-emerald-300 focus:border-emerald-500">
                  <SelectValue placeholder="Select a client from your business directory..." />
                </SelectTrigger>
                <SelectContent>
                  {businesses.map(business => (
                    <SelectItem key={business.id} value={business.id}>
                      <div className="flex items-center gap-2">
                        <span className="font-medium">{business.business_name}</span>
                        {business.hub_building && (
                          <span className="text-xs text-slate-500">• {business.hub_building}</span>
                        )}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          {/* Invoice Details Header */}
          <div className="flex items-start justify-between mb-6 pb-6 border-b border-blue-100">
            <div className="flex-1">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center">
                  <span className="text-white font-bold text-lg">📄</span>
                </div>
                <div>
                  <h2 className="text-xl font-bold text-slate-900">Invoice Details</h2>
                  <p className="text-sm text-slate-500">Event: {formData.event_name || "Internal Support"}</p>
                </div>
              </div>
              
              <div className="bg-gradient-to-r from-blue-50 to-blue-100 p-4 rounded-lg mb-4">
                <div className="text-xs text-blue-600 font-semibold mb-1">Invoice Number</div>
                <div className="font-bold text-2xl text-blue-900">{formData.invoice_number}</div>
              </div>
              
              <div className="grid grid-cols-2 gap-4 mb-4">
                <div>
                  <Label className="text-xs font-semibold text-slate-700">Invoice Date</Label>
                  <Input
                    type="date"
                    value={formData.invoice_date}
                    onChange={(e) => setFormData({ ...formData, invoice_date: e.target.value })}
                    className="mt-1 border-blue-200 focus:border-blue-500"
                  />
                </div>
                <div>
                  <Label className="text-xs font-semibold text-slate-700">Due Date</Label>
                  <Input
                    type="date"
                    value={formData.due_date}
                    onChange={(e) => setFormData({ ...formData, due_date: e.target.value })}
                    className="mt-1 border-blue-200 focus:border-blue-500"
                  />
                </div>
              </div>

              <div className="mb-4">
                <Label className="text-xs">Hub</Label>
                <Input
                  value={formData.hub}
                  onChange={(e) => setFormData({ ...formData, hub: e.target.value })}
                  placeholder="Hub"
                  className="mt-1"
                />
              </div>

              <div className="mb-4">
                <Label className="text-xs">Manager</Label>
                <Input
                  value={formData.manager}
                  onChange={(e) => setFormData({ ...formData, manager: e.target.value })}
                  placeholder="Manager Name"
                  className="mt-1"
                />
              </div>

              <div>
                <Label className="text-xs">Vendor #</Label>
                <Input
                  value={formData.vendor_id}
                  onChange={(e) => setFormData({ ...formData, vendor_id: e.target.value })}
                  placeholder="Vendor #"
                  className="mt-1"
                />
              </div>
            </div>

            <div className="flex-1 text-right">
              <div className="mb-4">
                <Label className="text-xs font-semibold text-slate-700 block mb-2">Payment Terms</Label>
                <div className="flex gap-2 justify-end">
                  <Badge 
                    className={`cursor-pointer transition-all ${formData.payment_terms === "30" ? "bg-blue-600 text-white" : "bg-white border-2 border-slate-200 text-slate-700 hover:border-blue-300"}`}
                    onClick={() => setFormData({ ...formData, payment_terms: "30", due_date: format(addDays(new Date(formData.invoice_date), 30), 'yyyy-MM-dd') })}
                  >
                    30 days
                  </Badge>
                  <Badge 
                    className={`cursor-pointer transition-all ${formData.payment_terms === "45" ? "bg-blue-600 text-white" : "bg-white border-2 border-slate-200 text-slate-700 hover:border-blue-300"}`}
                    onClick={() => setFormData({ ...formData, payment_terms: "45", due_date: format(addDays(new Date(formData.invoice_date), 45), 'yyyy-MM-dd') })}
                  >
                    45 days
                  </Badge>
                  <Badge 
                    className={`cursor-pointer transition-all ${formData.payment_terms === "60" ? "bg-blue-600 text-white" : "bg-white border-2 border-slate-200 text-slate-700 hover:border-blue-300"}`}
                    onClick={() => setFormData({ ...formData, payment_terms: "60", due_date: format(addDays(new Date(formData.invoice_date), 60), 'yyyy-MM-dd') })}
                  >
                    60 days
                  </Badge>
                </div>
              </div>
              
              <div className="mt-10 space-y-3">
                <div className="flex items-center gap-2 justify-end">
                  <span className="text-sm text-slate-500">Department:</span>
                  <Input
                    value={formData.department}
                    onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                    placeholder="INV-G00G20242"
                    className="h-8 w-48"
                  />
                </div>
                <div className="flex items-center gap-2 justify-end">
                  <span className="text-sm text-slate-500">PO#:</span>
                  <Input
                    value={formData.po_reference}
                    onChange={(e) => setFormData({ ...formData, po_reference: e.target.value })}
                    placeholder="INV-G00G20242"
                    className="h-8 w-48"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* From and To - Compact */}
          <div className="grid grid-cols-2 gap-4 mb-6">
            <div className="bg-blue-50/50 p-3 rounded-lg border border-blue-100">
              <div className="flex items-center gap-2 mb-2">
                <div className="w-6 h-6 bg-blue-600 rounded flex items-center justify-center text-white text-xs font-bold">F</div>
                <span className="text-xs font-semibold text-blue-900">From (Vendor)</span>
              </div>
              <div className="text-sm space-y-0.5">
                <input
                  value={formData.from_company.name}
                  onChange={(e) => setFormData({ ...formData, from_company: { ...formData.from_company, name: e.target.value } })}
                  className="w-full font-medium text-slate-900 bg-transparent border-0 border-b border-transparent hover:border-blue-200 focus:border-blue-400 focus:outline-none py-0.5 transition-colors"
                />
                <input
                  value={formData.from_company.address}
                  onChange={(e) => setFormData({ ...formData, from_company: { ...formData.from_company, address: e.target.value } })}
                  className="w-full text-slate-600 bg-transparent border-0 border-b border-transparent hover:border-blue-200 focus:border-blue-400 focus:outline-none py-0.5 text-xs transition-colors"
                />
                <input
                  value={formData.from_company.phone}
                  onChange={(e) => setFormData({ ...formData, from_company: { ...formData.from_company, phone: e.target.value } })}
                  className="w-full text-xs text-slate-500 bg-transparent border-0 border-b border-transparent hover:border-blue-200 focus:border-blue-400 focus:outline-none py-0.5 transition-colors"
                />
                <input
                  value={formData.from_company.email}
                  onChange={(e) => setFormData({ ...formData, from_company: { ...formData.from_company, email: e.target.value } })}
                  className="w-full text-xs text-slate-500 bg-transparent border-0 border-b border-transparent hover:border-blue-200 focus:border-blue-400 focus:outline-none py-0.5 transition-colors"
                />
              </div>
            </div>

            <div className="bg-emerald-50/50 p-3 rounded-lg border border-emerald-200">
              <div className="flex items-center gap-2 mb-2">
                <div className="w-6 h-6 bg-emerald-600 rounded-full flex items-center justify-center text-white text-xs font-bold">T</div>
                <span className="text-xs font-semibold text-slate-900">To:</span>
              </div>
              <div className="space-y-1 text-sm">
                <input
                  value={formData.to_company.name}
                  onChange={(e) => setFormData({ ...formData, to_company: { ...formData.to_company, name: e.target.value } })}
                  placeholder="Company"
                  className="w-full font-semibold text-slate-900 bg-transparent border-0 border-b border-transparent hover:border-slate-300 focus:border-blue-400 focus:outline-none py-0.5 transition-colors"
                />
                <input
                  value={formData.to_company.hub_name}
                  onChange={(e) => setFormData({ ...formData, to_company: { ...formData.to_company, hub_name: e.target.value } })}
                  placeholder="Hub"
                  className="w-full text-slate-600 bg-transparent border-0 border-b border-transparent hover:border-slate-300 focus:border-blue-400 focus:outline-none py-0.5 transition-colors text-xs"
                />
                <div className="flex gap-4 text-xs">
                  <input
                    value={formData.department}
                    onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                    placeholder="Department"
                    className="flex-1 text-slate-600 bg-transparent border-0 border-b border-transparent hover:border-slate-300 focus:border-blue-400 focus:outline-none py-0.5 transition-colors"
                  />
                  <input
                    value={formData.po_reference}
                    onChange={(e) => setFormData({ ...formData, po_reference: e.target.value })}
                    placeholder="Cost Center"
                    className="flex-1 text-slate-600 bg-transparent border-0 border-b border-transparent hover:border-slate-300 focus:border-blue-400 focus:outline-none py-0.5 transition-colors"
                  />
                </div>
                <input
                  value={formData.to_company.address}
                  onChange={(e) => setFormData({ ...formData, to_company: { ...formData.to_company, address: e.target.value } })}
                  placeholder="Main Business Address"
                  className="w-full text-slate-600 bg-transparent border-0 border-b border-transparent hover:border-slate-300 focus:border-blue-400 focus:outline-none py-0.5 transition-colors text-xs"
                />
                <div className="flex gap-4 text-xs">
                  <input
                    value={formData.to_company.phone}
                    onChange={(e) => setFormData({ ...formData, to_company: { ...formData.to_company, phone: e.target.value } })}
                    placeholder="Phone"
                    className="flex-1 text-slate-600 bg-transparent border-0 border-b border-transparent hover:border-slate-300 focus:border-blue-400 focus:outline-none py-0.5 transition-colors"
                  />
                  <input
                    value={formData.to_company.email}
                    onChange={(e) => setFormData({ ...formData, to_company: { ...formData.to_company, email: e.target.value } })}
                    placeholder="Email"
                    className="flex-1 text-slate-600 bg-transparent border-0 border-b border-transparent hover:border-slate-300 focus:border-blue-400 focus:outline-none py-0.5 transition-colors"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* Staff Table */}
          <div className="mb-6">
            <div className="flex items-center justify-between mb-4 p-4 bg-gradient-to-r from-blue-50 to-blue-100 rounded-lg">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center">
                  <span className="text-white font-bold text-lg">👥</span>
                </div>
                <div>
                  <h3 className="font-bold text-blue-900">Staff Entries</h3>
                  <p className="text-xs text-blue-700">{formData.staff_entries.length} entries</p>
                </div>
              </div>
              <Button size="sm" onClick={handleAddStaffEntry} className="bg-blue-600 hover:bg-blue-700 text-white shadow-md">
                <Plus className="w-4 h-4 mr-1" />
                Add Staff Entry
              </Button>
            </div>
            
            <div className="border rounded-lg">
              <table className="w-full text-sm table-fixed">
                <thead className="bg-slate-50">
                  <tr>
                    <th className="p-2 text-left w-10">#</th>
                    <th className="p-2 text-left w-32">Name</th>
                    <th className="p-2 text-left w-28">Position</th>
                    <th className="p-2 text-left w-24">ClockIn</th>
                    <th className="p-2 text-left w-16">Lunch</th>
                    <th className="p-2 text-left w-24">Checkout</th>
                    <th className="p-2 text-left w-16">Wrkd</th>
                    <th className="p-2 text-left w-14">Reg</th>
                    <th className="p-2 text-left w-14">OT</th>
                    <th className="p-2 text-left w-14">DT</th>
                    <th className="p-2 text-left w-16">Rate</th>
                    <th className="p-2 text-right w-16">Reg$</th>
                    <th className="p-2 text-right w-16">OT$</th>
                    <th className="p-2 text-right w-16">DT$</th>
                    <th className="p-2 text-right w-20">Total</th>
                    <th className="p-2 w-10"></th>
                  </tr>
                </thead>
                <tbody>
                  {formData.staff_entries.map((entry, idx) => (
                    <tr key={idx} className={`border-t hover:bg-slate-50 ${disputedIndices.includes(idx) ? 'bg-red-50 border-l-4 border-l-red-500' : ''}`}>
                      <td className="p-1 text-xs">
                        {disputedIndices.includes(idx) && (
                          <span className="inline-flex items-center justify-center w-4 h-4 bg-red-500 text-white rounded-full text-[10px] mr-0.5" title="Disputed">!</span>
                        )}
                        {idx + 1}
                      </td>
                      <td className="p-1">
                        <Popover>
                          <PopoverTrigger asChild>
                            <Button variant="outline" size="sm" className="h-7 w-full justify-start font-normal truncate text-xs px-2">
                              {entry.name || <span className="text-slate-400">Select</span>}
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="w-64 p-2" align="start">
                            <Input
                              placeholder="Search staff..."
                              className="mb-2 h-8"
                              onChange={(e) => {
                                const searchInput = e.target;
                                searchInput.dataset.search = e.target.value.toLowerCase();
                                searchInput.parentElement.querySelectorAll('[data-staff-item]').forEach(item => {
                                  item.style.display = item.dataset.staffItem.toLowerCase().includes(searchInput.dataset.search) ? 'block' : 'none';
                                });
                              }}
                            />
                            <div className="max-h-48 overflow-y-auto space-y-1">
                              {staffDirectory.map(staff => (
                                <button
                                  key={staff.id}
                                  data-staff-item={staff.employee_name}
                                  onClick={() => {
                                    handleStaffChange(idx, 'name', staff.employee_name);
                                  }}
                                  className="w-full text-left px-2 py-1.5 text-sm rounded hover:bg-blue-50 hover:text-blue-700 transition-colors"
                                >
                                  <span>{staff.employee_name}</span>
                                  {staff.position && <span className="text-xs text-slate-400 ml-1">• {staff.position}</span>}
                                </button>
                              ))}
                            </div>
                          </PopoverContent>
                        </Popover>
                      </td>
                      <td className="p-1">
                        <Select
                          value={entry.position || ""}
                          onValueChange={(val) => handlePositionChange(idx, val)}
                        >
                          <SelectTrigger className="h-7 w-full text-xs">
                            <SelectValue placeholder="Position" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="Line Cook">Line Cook</SelectItem>
                            <SelectItem value="Prep Cook">Prep Cook</SelectItem>
                            <SelectItem value="Sous Chef">Sous Chef</SelectItem>
                            <SelectItem value="Executive Chef">Executive Chef</SelectItem>
                            <SelectItem value="Server">Server</SelectItem>
                            <SelectItem value="Bartender">Bartender</SelectItem>
                            <SelectItem value="Barback">Barback</SelectItem>
                            <SelectItem value="Host">Host</SelectItem>
                            <SelectItem value="Busser">Busser</SelectItem>
                            <SelectItem value="Dishwasher">Dishwasher</SelectItem>
                            <SelectItem value="Food Runner">Food Runner</SelectItem>
                            <SelectItem value="Catering Staff">Catering Staff</SelectItem>
                            <SelectItem value="Event Staff">Event Staff</SelectItem>
                            <SelectItem value="Supervisor">Supervisor</SelectItem>
                            <SelectItem value="Manager">Manager</SelectItem>
                          </SelectContent>
                        </Select>
                      </td>
                      <td className="p-1">
                        <Popover open={timePickerOpen === `checkin-${idx}`} onOpenChange={(open) => setTimePickerOpen(open ? `checkin-${idx}` : null)}>
                          <PopoverTrigger asChild>
                            <Button variant="outline" size="sm" className="h-7 w-full justify-start font-normal text-xs px-1">
                              <Clock className="w-3 h-3 mr-0.5" />
                              {entry.check_in}
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="w-52 p-3" align="start">
                            <div className="space-y-3">
                              <div className="flex items-center justify-center gap-1 bg-slate-50 rounded-lg p-2">
                                <Select value={selectedTime.hours} onValueChange={(val) => setSelectedTime({ ...selectedTime, hours: val })}>
                                  <SelectTrigger className="w-14 h-9 text-base font-semibold border-0 bg-white shadow-sm justify-center">
                                    <SelectValue placeholder="09" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0')).map(h => (
                                      <SelectItem key={h} value={h}>{h}</SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                                <span className="text-base font-bold text-slate-400">:</span>
                                <Select value={selectedTime.minutes} onValueChange={(val) => setSelectedTime({ ...selectedTime, minutes: val })}>
                                  <SelectTrigger className="w-14 h-9 text-base font-semibold border-0 bg-white shadow-sm justify-center">
                                    <SelectValue placeholder="00" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {['00', '15', '30', '45'].map(m => (
                                      <SelectItem key={m} value={m}>{m}</SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                                <div className="flex gap-0.5 ml-1">
                                  <button
                                    type="button"
                                    onClick={() => setSelectedTime({ ...selectedTime, period: 'AM' })}
                                    className={`px-2 py-1.5 text-[10px] font-bold rounded transition-all ${selectedTime.period === 'AM' ? 'bg-blue-600 text-white' : 'bg-white text-slate-500 hover:bg-slate-100'}`}
                                  >
                                    AM
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => setSelectedTime({ ...selectedTime, period: 'PM' })}
                                    className={`px-2 py-1.5 text-[10px] font-bold rounded transition-all ${selectedTime.period === 'PM' ? 'bg-blue-600 text-white' : 'bg-white text-slate-500 hover:bg-slate-100'}`}
                                  >
                                    PM
                                  </button>
                                </div>
                              </div>
                              <div className="grid grid-cols-4 gap-1">
                                {['6AM', '7AM', '8AM', '9AM', '10AM', '11AM', '12PM', '1PM'].map((label, i) => {
                                  const times = ['06:00 AM', '07:00 AM', '08:00 AM', '09:00 AM', '10:00 AM', '11:00 AM', '12:00 PM', '01:00 PM'];
                                  return (
                                    <button
                                      key={label}
                                      type="button"
                                      onClick={() => {
                                        handleStaffChange(idx, 'check_in', times[i]);
                                        setTimePickerOpen(null);
                                      }}
                                      className="px-1 py-1 text-[10px] bg-slate-100 hover:bg-blue-500 hover:text-white rounded transition-colors font-medium"
                                    >
                                      {label}
                                    </button>
                                  );
                                })}
                              </div>
                              <Button size="sm" onClick={() => handleTimeSelect(idx, 'check_in')} className="w-full h-7 text-xs bg-blue-600 hover:bg-blue-700">
                                Set
                              </Button>
                            </div>
                          </PopoverContent>
                        </Popover>
                      </td>
                      <td className="p-1">
                        <Select
                          value={entry.lunch === "NB" ? "NB" : String(entry.lunch || 0)}
                          onValueChange={(val) => handleStaffChange(idx, 'lunch', val === "NB" ? "NB" : parseInt(val))}
                        >
                          <SelectTrigger className="h-7 w-full text-xs">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="NB">NB</SelectItem>
                            <SelectItem value="5">5</SelectItem>
                            <SelectItem value="10">10</SelectItem>
                            <SelectItem value="15">15</SelectItem>
                            <SelectItem value="20">20</SelectItem>
                            <SelectItem value="25">25</SelectItem>
                            <SelectItem value="30">30</SelectItem>
                            <SelectItem value="45">45</SelectItem>
                            <SelectItem value="60">60</SelectItem>
                          </SelectContent>
                        </Select>
                      </td>
                      <td className="p-1">
                        <Popover open={timePickerOpen === `checkout-${idx}`} onOpenChange={(open) => setTimePickerOpen(open ? `checkout-${idx}` : null)}>
                          <PopoverTrigger asChild>
                            <Button variant="outline" size="sm" className="h-7 w-full justify-start font-normal text-xs px-1">
                              <Clock className="w-3 h-3 mr-0.5" />
                              {entry.check_out || "hh:mm"}
                            </Button>
                          </PopoverTrigger>
                          <PopoverContent className="w-52 p-3" align="start">
                            <div className="space-y-3">
                              <div className="flex items-center justify-center gap-1 bg-slate-50 rounded-lg p-2">
                                <Select value={selectedTime.hours} onValueChange={(val) => setSelectedTime({ ...selectedTime, hours: val })}>
                                  <SelectTrigger className="w-14 h-9 text-base font-semibold border-0 bg-white shadow-sm justify-center">
                                    <SelectValue placeholder="09" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0')).map(h => (
                                      <SelectItem key={h} value={h}>{h}</SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                                <span className="text-base font-bold text-slate-400">:</span>
                                <Select value={selectedTime.minutes} onValueChange={(val) => setSelectedTime({ ...selectedTime, minutes: val })}>
                                  <SelectTrigger className="w-14 h-9 text-base font-semibold border-0 bg-white shadow-sm justify-center">
                                    <SelectValue placeholder="00" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    {['00', '15', '30', '45'].map(m => (
                                      <SelectItem key={m} value={m}>{m}</SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                                <div className="flex gap-0.5 ml-1">
                                  <button
                                    type="button"
                                    onClick={() => setSelectedTime({ ...selectedTime, period: 'AM' })}
                                    className={`px-2 py-1.5 text-[10px] font-bold rounded transition-all ${selectedTime.period === 'AM' ? 'bg-blue-600 text-white' : 'bg-white text-slate-500 hover:bg-slate-100'}`}
                                  >
                                    AM
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => setSelectedTime({ ...selectedTime, period: 'PM' })}
                                    className={`px-2 py-1.5 text-[10px] font-bold rounded transition-all ${selectedTime.period === 'PM' ? 'bg-blue-600 text-white' : 'bg-white text-slate-500 hover:bg-slate-100'}`}
                                  >
                                    PM
                                  </button>
                                </div>
                              </div>
                              <div className="grid grid-cols-4 gap-1">
                                {['2PM', '3PM', '4PM', '5PM', '6PM', '7PM', '8PM', '9PM'].map((label, i) => {
                                  const times = ['02:00 PM', '03:00 PM', '04:00 PM', '05:00 PM', '06:00 PM', '07:00 PM', '08:00 PM', '09:00 PM'];
                                  return (
                                    <button
                                      key={label}
                                      type="button"
                                      onClick={() => {
                                        handleStaffChange(idx, 'check_out', times[i]);
                                        setTimePickerOpen(null);
                                      }}
                                      className="px-1 py-1 text-[10px] bg-slate-100 hover:bg-blue-500 hover:text-white rounded transition-colors font-medium"
                                    >
                                      {label}
                                    </button>
                                  );
                                })}
                              </div>
                              <Button size="sm" onClick={() => handleTimeSelect(idx, 'check_out')} className="w-full h-7 text-xs bg-blue-600 hover:bg-blue-700">
                                Set
                              </Button>
                            </div>
                          </PopoverContent>
                        </Popover>
                      </td>
                      <td className="p-1">
                        <Input
                          type="number"
                          step="0.1"
                          value={entry.worked_hours}
                          onChange={(e) => handleStaffChange(idx, 'worked_hours', parseFloat(e.target.value))}
                          className="h-7 w-14 text-xs px-1"
                        />
                      </td>
                      <td className="p-1">
                        <Input
                          type="number"
                          step="0.1"
                          value={entry.regular_hours}
                          onChange={(e) => handleStaffChange(idx, 'regular_hours', parseFloat(e.target.value))}
                          className="h-7 w-12 text-xs px-1"
                        />
                      </td>
                      <td className="p-1">
                        <Input
                          type="number"
                          step="0.1"
                          value={entry.ot_hours}
                          onChange={(e) => handleStaffChange(idx, 'ot_hours', parseFloat(e.target.value))}
                          className="h-7 w-12 text-xs px-1"
                        />
                      </td>
                      <td className="p-1">
                        <Input
                          type="number"
                          step="0.1"
                          value={entry.dt_hours}
                          onChange={(e) => handleStaffChange(idx, 'dt_hours', parseFloat(e.target.value))}
                          className="h-7 w-12 text-xs px-1"
                        />
                      </td>
                      <td className="p-1">
                        <Input
                          type="number"
                          step="0.01"
                          value={entry.rate}
                          onChange={(e) => handleStaffChange(idx, 'rate', parseFloat(e.target.value))}
                          className="h-7 w-14 text-xs px-1"
                        />
                      </td>
                      <td className="p-1 text-right text-xs">${entry.regular_value?.toFixed(0) || "0"}</td>
                      <td className="p-1 text-right text-xs">${entry.ot_value?.toFixed(0) || "0"}</td>
                      <td className="p-1 text-right text-xs">${entry.dt_value?.toFixed(0) || "0"}</td>
                      <td className="p-1 text-right font-semibold text-xs">${entry.total?.toFixed(2) || "0"}</td>
                      <td className="p-1 text-center">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveStaff(idx)}
                          className="h-6 w-6 p-0 text-red-600 hover:bg-red-50"
                        >
                          <Trash2 className="w-3 h-3" />
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Charges */}
          <div className="mb-6">
            <div className="flex items-center justify-between mb-4 p-4 bg-gradient-to-r from-green-50 to-emerald-100 rounded-lg">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-emerald-600 rounded-lg flex items-center justify-center">
                  <span className="text-white font-bold text-lg">💰</span>
                </div>
                <div>
                  <h3 className="font-bold text-emerald-900">Additional Charges</h3>
                  <p className="text-xs text-emerald-700">{formData.charges.length} charges</p>
                </div>
              </div>
              <Button size="sm" onClick={handleAddCharge} className="bg-emerald-600 hover:bg-emerald-700 text-white shadow-md">
                <Plus className="w-4 h-4 mr-1" />
                Add Charge
              </Button>
            </div>
            
            <div className="overflow-x-auto border rounded-lg">
              <table className="w-full text-sm">
                <thead className="bg-slate-50">
                  <tr>
                    <th className="p-2 text-left">#</th>
                    <th className="p-2 text-left">Name</th>
                    <th className="p-2 text-left">QTY</th>
                    <th className="p-2 text-left">Rate</th>
                    <th className="p-2 text-left">Price</th>
                    <th className="p-2">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {formData.charges.map((charge, idx) => (
                    <tr key={idx} className="border-t hover:bg-slate-50">
                      <td className="p-2">{idx + 1}</td>
                      <td className="p-2">
                        <Input
                          value={charge.name}
                          onChange={(e) => handleChargeChange(idx, 'name', e.target.value)}
                          className="h-8"
                        />
                      </td>
                      <td className="p-2">
                        <Input
                          type="number"
                          step="0.01"
                          value={charge.qty}
                          onChange={(e) => handleChargeChange(idx, 'qty', parseFloat(e.target.value))}
                          className="h-8 w-20"
                        />
                      </td>
                      <td className="p-2">
                        <Input
                          type="number"
                          step="0.01"
                          value={charge.rate}
                          onChange={(e) => handleChargeChange(idx, 'rate', parseFloat(e.target.value))}
                          className="h-8 w-20"
                        />
                      </td>
                      <td className="p-2">${charge.price?.toFixed(2) || "0.00"}</td>
                      <td className="p-2 text-center">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveCharge(idx)}
                          className="h-8 w-8 p-0 text-red-600 hover:bg-red-50"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Totals */}
          <div className="flex justify-end mb-6">
            <div className="w-96 bg-gradient-to-br from-blue-50 to-blue-100 p-6 rounded-xl border-2 border-blue-200 shadow-lg">
              <div className="space-y-4">
                <div className="flex justify-between text-sm">
                  <span className="text-slate-600">Sub total:</span>
                  <span className="font-semibold text-slate-900">${totals.subtotal.toFixed(2)}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-slate-600">Other charges:</span>
                  <Input
                    type="number"
                    step="0.01"
                    value={formData.other_charges}
                    onChange={(e) => setFormData({ ...formData, other_charges: e.target.value })}
                    className="h-9 w-32 text-right border-blue-300 focus:border-blue-500 bg-white"
                  />
                </div>
                <div className="flex justify-between text-xl font-bold pt-4 border-t-2 border-blue-300">
                  <span className="text-blue-900">Grand total:</span>
                  <span className="text-blue-900">${totals.grandTotal.toFixed(2)}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Notes */}
          <div className="mb-6">
            <Label className="mb-2 block">Notes</Label>
            <Textarea
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              placeholder="Enter your notes here..."
              rows={3}
            />
          </div>

          {/* Actions */}
          <div className="flex justify-between items-center pt-6 border-t-2 border-blue-100">
            <Button variant="outline" onClick={() => navigate(createPageUrl('Invoices'))} className="border-slate-300">
              Cancel
            </Button>
            <div className="flex gap-3">
              <Button
                variant="outline"
                onClick={() => saveMutation.mutate({ ...formData, status: "Draft" })}
                disabled={saveMutation.isPending}
                className="border-blue-300 text-blue-700 hover:bg-blue-50"
              >
                Save as Draft
              </Button>
              <Button
                variant="outline"
                onClick={() => saveMutation.mutate(formData)}
                disabled={saveMutation.isPending}
                className="border-slate-300 text-slate-700 hover:bg-slate-50"
              >
                {saveMutation.isPending ? "Saving..." : isEdit ? "Update Invoice" : "Create Invoice"}
              </Button>
              <Button
                onClick={async () => {
                  const invoiceData = { ...formData, status: "Pending Review" };
                  await saveMutation.mutateAsync(invoiceData);
                  const emailResult = await sendEmailMutation.mutateAsync({
                    ...invoiceData,
                    amount: calculateTotals().grandTotal
                  });
                  if (emailResult?.sent) {
                    toast({
                      title: "📧 Email Sent",
                      description: `Invoice emailed to ${invoiceData.to_company?.email}`,
                    });
                  } else {
                    toast({
                      title: "✅ Invoice Sent",
                      description: "Invoice is now pending client review in the portal",
                    });
                  }
                }}
                disabled={saveMutation.isPending || sendEmailMutation.isPending}
                className="bg-gradient-to-r from-emerald-600 to-emerald-700 hover:from-emerald-700 hover:to-emerald-800 text-white font-semibold px-8 shadow-lg"
              >
                {saveMutation.isPending || sendEmailMutation.isPending ? "Sending..." : "Send to Client"}
              </Button>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}