import { Badge } from "@/common/components/ui/badge";
import { Button } from "@/common/components/ui/button";
import { Card } from "@/common/components/ui/card";
import { Input } from "@/common/components/ui/input";
import { Label } from "@/common/components/ui/label";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/common/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/common/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/common/components/ui/table";
import { Textarea } from "@/common/components/ui/textarea";
import { useToast } from "@/common/components/ui/use-toast";
import { InvoiceStatus, InovicePaymentTerms } from "@/dataconnect-generated";
import { 
  useCreateInvoice, 
  useCreateInvoiceTemplate, 
  useDeleteInvoiceTemplate, 
  useGetInvoiceById, 
  useListBusinesses, 
  useListInvoices, 
  useListInvoiceTemplates, 
  useListOrders, 
  useListStaff, 
  useListVendorRates, 
  useUpdateInvoice 
} from "@/dataconnect-generated/react";
import { dataConnect } from "@/features/auth/firebase";
import DashboardLayout from "@/features/layouts/DashboardLayout";
import { addDays, format, parseISO } from "date-fns";
import { ArrowLeft, Building2, Calendar, Clock, FileText, Mail, Phone, Plus, Trash2, User } from "lucide-react";
import { useEffect, useState } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";

// Helper to convert 24h to 12h format
const convertTo12Hour = (time24?: string) => {
  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}`;
};

export default function InvoiceEditor() {
  const navigate = useNavigate();
  const { id: pathId } = useParams<{ id: string }>();
  const { toast } = useToast();
  const [searchParams] = useSearchParams();
  
  const invoiceId = searchParams.get('id');
  const disputedIndices = searchParams.get('disputed')?.split(',').map(Number).filter(n => !isNaN(n)) || [];
  
  const effectiveInvoiceId = invoiceId || (pathId !== 'new' ? pathId : null);
  const isEdit = !!effectiveInvoiceId;

  // Data Connect Queries
  const { data: invoicesData } = useListInvoices(dataConnect);
  const invoices = invoicesData?.invoices || [];

  const { data: eventsData } = useListOrders(dataConnect);
  const events = eventsData?.orders || [];

  const { data: businessesData } = useListBusinesses(dataConnect);
  const businesses = businessesData?.businesses || [];

  const { data: vendorRatesData } = useListVendorRates(dataConnect);
  const vendorRates = vendorRatesData?.vendorRates || [];

  const { data: staffData } = useListStaff(dataConnect);
  const staffDirectory = staffData?.staffs || [];

  const { data: templatesData, refetch: refetchTemplates } = useListInvoiceTemplates(dataConnect);
  const templates = templatesData?.invoiceTemplates || [];

  const { data: currentInvoiceData } = useGetInvoiceById(dataConnect, { id: effectiveInvoiceId || "" }, { enabled: isEdit && !!effectiveInvoiceId });
  const existingInvoice = currentInvoiceData?.invoice;

  const [selectedClientId, setSelectedClientId] = useState("");

  useEffect(() => {
    if (existingInvoice) {
      setSelectedClientId(existingInvoice.businessId);
    }
  }, [existingInvoice]);

  // Generate sequential invoice number based on client prefix
  const generateInvoiceNumber = (clientName: string, existingInvoices: any[]) => {
    const extractCompanyName = (name: string) => {
      if (!name) return '';
      return name.split(/\s*[-–]\s*/)[0].trim();
    };

    const generatePrefix = (name: string) => {
      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) {
        return words[0].substring(0, 4).toUpperCase();
      } else {
        return words.slice(0, 4).map(w => w[0]).join('').toUpperCase();
      }
    };

    const prefix = generatePrefix(clientName);

    const existingNumbers = (existingInvoices || [])
      .filter(inv => inv.invoiceNumber?.startsWith(prefix + '-'))
      .map(inv => {
        const match = inv.invoiceNumber.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<any>({
    invoice_number: "",
    event_id: "",
    event_name: "",
    invoice_date: format(new Date(), 'yyyy-MM-dd'),
    due_date: format(addDays(new Date(), 45), 'yyyy-MM-dd'),
    payment_terms: "NET_45",
    hub: "",
    manager: "",
    vendor_id: "",
    department: "",
    po_reference: "",
    from_company: {
      name: "KROW Workforce",
      address: "848 E Gish Rd Ste 1, San Jose, CA 95112",
      phone: "(408) 936-0180",
      email: "billing@krowworkforce.com"
    },
    to_company: {
      name: "",
      phone: "",
      email: "",
      address: "",
      manager_name: "",
      hub_name: "",
      vendor_id: ""
    },
    staff_entries: [],
    charges: [],
    other_charges: 0,
    notes: "",
  });

  useEffect(() => {
    if (existingInvoice) {
      setFormData({
        invoice_number: existingInvoice.invoiceNumber,
        event_id: existingInvoice.orderId || "",
        event_name: existingInvoice.order?.eventName || "",
        invoice_date: existingInvoice.issueDate ? format(parseISO(existingInvoice.issueDate as string), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd'),
        due_date: existingInvoice.dueDate ? format(parseISO(existingInvoice.dueDate as string), 'yyyy-MM-dd') : format(addDays(new Date(), 45), 'yyyy-MM-dd'),
        payment_terms: existingInvoice.paymentTerms || "NET_45",
        hub: existingInvoice.hub || "",
        manager: existingInvoice.managerName || "",
        vendor_id: existingInvoice.vendorNumber || "",
        department: existingInvoice.order?.deparment || "",
        po_reference: existingInvoice.order?.poReference || "",
        from_company: {
          name: existingInvoice.vendor?.companyName || "KROW Workforce",
          address: existingInvoice.vendor?.address || "848 E Gish Rd Ste 1, San Jose, CA 95112",
          phone: existingInvoice.vendor?.phone || "(408) 936-0180",
          email: existingInvoice.vendor?.email || "billing@krowworkforce.com"
        },
        to_company: {
          name: existingInvoice.business?.businessName || "",
          phone: existingInvoice.business?.phone || "",
          email: existingInvoice.business?.email || "",
          address: existingInvoice.business?.address || "",
          manager_name: existingInvoice.business?.contactName || "",
          hub_name: existingInvoice.hub || "",
          vendor_id: existingInvoice.vendorNumber || ""
        },
        staff_entries: existingInvoice.roles || [],
        charges: existingInvoice.charges || [],
        other_charges: existingInvoice.otherCharges || 0,
        notes: existingInvoice.notes || "",
      });
    } else if (invoices.length > 0 && !formData.invoice_number) {
      setFormData((prev: any) => ({ ...prev, invoice_number: generateInvoiceNumber('', invoices) }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [existingInvoice, invoices]);

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

  const getRateForPosition = (position: string) => {
    const selectedBusiness = businesses.find(b => b.id === selectedClientId);
    if (!selectedBusiness || !position) return 0;

    const businessName = selectedBusiness.businessName || "";
    const extractCompanyName = (name: string) => {
      if (!name) return '';
      return name.split(/\s*[-–]\s*/)[0].trim();
    };
    const mainCompanyName = extractCompanyName(businessName);

    // Logic similar to MVP
    const clientSpecificRate = vendorRates.find(rate =>
      rate.roleName?.toLowerCase() === position.toLowerCase() &&
      rate.client_name === businessName // This field might be different in Data Connect, checking listVendorRates output
    );

    if (clientSpecificRate) return clientSpecificRate.clientRate || 0;

    const defaultRate = vendorRates.find(rate =>
      rate.roleName?.toLowerCase() === position.toLowerCase()
    );

    return defaultRate?.clientRate || 0;
  };

  const handleClientSelect = (clientId: string) => {
    setSelectedClientId(clientId);
    const selectedBusiness = businesses.find(b => b.id === clientId);

    if (selectedBusiness) {
      const hubName = selectedBusiness.hubBuilding || "";
      const newInvoiceNumber = generateInvoiceNumber(selectedBusiness.businessName, invoices);

      setFormData((prev: any) => ({
        ...prev,
        invoice_number: isEdit ? prev.invoice_number : newInvoiceNumber,
        to_company: {
          name: selectedBusiness.businessName || "",
          phone: selectedBusiness.phone || "",
          email: selectedBusiness.email || "",
          address: selectedBusiness.address || "",
          manager_name: selectedBusiness.contactName || "",
          hub_name: hubName,
          vendor_id: "" // erp_vendor_id was not in business query, assuming empty for now
        },
        hub: hubName,
        manager: selectedBusiness.contactName || "",
        department: "",
        po_reference: ""
      }));
    }
  };

  const handleImportFromEvent = (event: any) => {
    const staffEntries = (event.assignedStaff || []).map((staff: any) => {
      const shift = (event.shifts as any[])?.[0];
      const role = shift?.roles?.find((r: any) => r.role === staff.role) || shift?.roles?.[0];

      return {
        name: staff.fullName || staff.staff_name || "",
        date: event.date ? format(parseISO(event.date as string), '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
      };
    });

    staffEntries.forEach((entry: any) => {
      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;
    });

    const business = businesses.find(b => b.id === event.businessId);

    setFormData((prev: any) => ({
      ...prev,
      event_id: event.id,
      event_name: event.eventName || "",
      hub: event.teamHub?.hubName || "",
      manager: event.business?.contactName || "",
      po_reference: event.poReference || "",
      to_company: business ? {
        name: business.businessName || "",
        phone: business.phone || "",
        email: business.email || "",
        address: business.address || "",
        manager_name: business.contactName || "",
        hub_name: event.teamHub?.hubName || "",
        vendor_id: ""
      } : {
        ...prev.to_company,
        name: event.business?.businessName || prev.to_company.name,
        hub_name: event.teamHub?.hubName || ""
      },
      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.eventName}`,
    });
  };

  const handleDuplicateInvoice = (invoice: any) => {
    const newStaffEntries = (invoice.roles || []).map((entry: any) => ({
      ...entry,
      date: format(new Date(), 'MM/dd/yyyy')
    }));

    const newInvoiceNumber = generateInvoiceNumber(invoice.business?.businessName || '', invoices);

    setFormData({
      invoice_number: newInvoiceNumber,
      event_id: "",
      event_name: invoice.order?.eventName || "",
      invoice_date: format(new Date(), 'yyyy-MM-dd'),
      due_date: format(addDays(new Date(), 45), 'yyyy-MM-dd'),
      payment_terms: invoice.paymentTerms || "NET_45",
      hub: invoice.hub || "",
      manager: invoice.managerName || "",
      vendor_id: invoice.vendorNumber || "",
      department: invoice.order?.deparment || "",
      po_reference: invoice.order?.poReference || "",
      from_company: {
        name: invoice.vendor?.companyName || formData.from_company.name,
        address: invoice.vendor?.address || formData.from_company.address,
        phone: invoice.vendor?.phone || formData.from_company.phone,
        email: invoice.vendor?.email || formData.from_company.email,
      },
      to_company: {
        name: invoice.business?.businessName || "",
        phone: invoice.business?.phone || "",
        email: invoice.business?.email || "",
        address: invoice.business?.address || "",
        manager_name: invoice.business?.contactName || "",
        hub_name: invoice.hub || "",
        vendor_id: invoice.vendorNumber || ""
      },
      staff_entries: newStaffEntries,
      charges: invoice.charges || [],
      other_charges: invoice.otherCharges || 0,
      notes: invoice.notes || "",
    });

    if (invoice.businessId) {
      setSelectedClientId(invoice.businessId);
    }

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

  const { mutate: createTemplate } = useCreateInvoiceTemplate(dataConnect);
  const { mutate: deleteTemplate } = useDeleteInvoiceTemplate(dataConnect);

  const handleUseTemplate = (template: any) => {
    const newStaffEntries = (template.roles || []).map((entry: any) => ({
      ...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
    }));

    const newInvoiceNumber = generateInvoiceNumber(template.business?.businessName || '', invoices);

    setFormData((prev: any) => ({
      ...prev,
      invoice_number: newInvoiceNumber,
      invoice_date: format(new Date(), 'yyyy-MM-dd'),
      due_date: format(addDays(new Date(), 45), 'yyyy-MM-dd'),
      payment_terms: template.paymentTerms || "NET_45",
      hub: template.hub || "",
      department: "",
      po_reference: template.order?.poReference || "",
      from_company: {
        name: template.vendor?.companyName || prev.from_company.name,
        address: template.vendor?.address || prev.from_company.address,
        phone: template.vendor?.phone || prev.from_company.phone,
        email: template.vendor?.email || prev.from_company.email,
      },
      to_company: {
        name: template.business?.businessName || "",
        phone: template.business?.phone || "",
        email: template.business?.email || "",
        address: template.business?.address || "",
        manager_name: template.business?.contactName || "",
        hub_name: template.hub || "",
        vendor_id: template.vendorNumber || ""
      },
      staff_entries: newStaffEntries,
      charges: template.charges || [],
      notes: template.notes || "",
    }));

    if (template.businessId) {
      setSelectedClientId(template.businessId);
    }

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

  const handleSaveTemplate = async (templateName: string) => {
    const selectedBusiness = businesses.find(b => b.id === selectedClientId);
    
    await createTemplate({
      name: templateName,
      ownerId: "00000000-0000-0000-0000-000000000000", // placeholder, usually from auth
      businessId: selectedClientId || undefined,
      vendorId: "00000000-0000-0000-0000-000000000000", // placeholder
      paymentTerms: formData.payment_terms as InovicePaymentTerms,
      invoiceNumber: formData.invoice_number,
      issueDate: new Date(formData.invoice_date).toISOString(),
      dueDate: new Date(formData.due_date).toISOString(),
      hub: formData.hub,
      managerName: formData.manager,
      roles: formData.staff_entries,
      charges: formData.charges,
      otherCharges: parseFloat(formData.other_charges) || 0,
      subtotal: totals.subtotal,
      amount: totals.grandTotal,
      notes: formData.notes,
      staffCount: formData.staff_entries.length,
      chargesCount: formData.charges.length,
    });
    
    refetchTemplates();

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

  const handleDeleteTemplate = async (templateId: string) => {
    await deleteTemplate({ id: templateId });
    refetchTemplates();
    toast({
      title: "Template Deleted",
      description: "Template has been removed",
    });
  };

  const parseTimeToMinutes = (timeStr: string) => {
    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: string, checkOut: string, lunch: string | number) => {
    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;

    if (lunch !== "NB" && (typeof lunch === 'number' ? lunch : parseInt(lunch)) >= 20) {
      totalMinutes -= (typeof lunch === 'number' ? lunch : parseInt(lunch));
    }
    return Math.max(0, totalMinutes / 60);
  };

  const calculateBillableHours = (checkIn: string, checkOut: string, lunch: string | number) => {
    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;

    let nbPenalty = 0;
    if (lunch === "NB") {
      nbPenalty = 1;
    } else if ((typeof lunch === 'number' ? lunch : parseInt(lunch)) >= 20) {
      totalMinutes -= (typeof lunch === 'number' ? lunch : parseInt(lunch));
    }
    return { total: Math.max(0, totalMinutes / 60), nbPenalty };
  };

  const handlePositionChange = (index: number, position: string) => {
    const rate = getRateForPosition(position);
    const newEntries = [...formData.staff_entries];
    newEntries[index] = {
      ...newEntries[index],
      position: position,
      rate: rate || newEntries[index].rate
    };

    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 });
  };

  const handleStaffChange = (index: number, field: string, value: any) => {
    const newEntries = [...formData.staff_entries];
    newEntries[index] = { ...newEntries[index], [field]: value };

    const entry = newEntries[index];

    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));

      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));
      }

      if (nbPenalty > 0) {
        entry.regular_hours = parseFloat((entry.regular_hours + nbPenalty).toFixed(2));
      }
    }

    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: number, field: string, value: any) => {
    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: number) => {
    setFormData({
      ...formData,
      staff_entries: formData.staff_entries.filter((_: any, i: number) => i !== index)
    });
  };

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

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

  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: 1,
          rate: 0,
          price: 0
        }
      ]
    });
  };

  const calculateTotals = () => {
    const staffTotal = formData.staff_entries.reduce((sum: number, entry: any) => sum + (entry.total || 0), 0);
    const chargesTotal = formData.charges.reduce((sum: number, charge: any) => 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();

  const { mutateAsync: createInvoice, isPending: creating } = useCreateInvoice(dataConnect);
  const { mutateAsync: updateInvoice, isPending: updating } = useUpdateInvoice(dataConnect);

  const handleSave = async (statusOverride?: string) => {
    const data = formData;
    const staffTotal = data.staff_entries.reduce((sum: number, entry: any) => sum + (entry.total || 0), 0);
    const chargesTotal = data.charges.reduce((sum: number, charge: any) => sum + ((charge.qty * charge.rate) || 0), 0);
    const subtotal = staffTotal + chargesTotal;
    const total = subtotal + (parseFloat(data.other_charges) || 0);

    const invoiceStatus = (statusOverride || (existingInvoice?.status === InvoiceStatus.DISPUTED ? InvoiceStatus.PENDING_REVIEW : (existingInvoice?.status || InvoiceStatus.DRAFT))) as InvoiceStatus;

    const payload = {
      status: invoiceStatus,
      vendorId: "00000000-0000-0000-0000-000000000000", // placeholder
      businessId: selectedClientId || "00000000-0000-0000-0000-000000000000", // placeholder
      orderId: data.event_id || "00000000-0000-0000-0000-000000000000", // placeholder
      paymentTerms: data.payment_terms as InovicePaymentTerms,
      invoiceNumber: data.invoice_number,
      issueDate: new Date(data.invoice_date).toISOString(),
      dueDate: new Date(data.due_date).toISOString(),
      hub: data.hub,
      managerName: data.manager,
      vendorNumber: data.vendor_id,
      roles: data.staff_entries,
      charges: data.charges,
      subtotal: subtotal,
      otherCharges: parseFloat(data.other_charges) || 0,
      amount: total,
      notes: data.notes,
      staffCount: data.staff_entries.length,
      chargesCount: data.charges.length,
    };

    try {
      if (effectiveInvoiceId) {
        await updateInvoice({ id: effectiveInvoiceId, ...payload });
      } else {
        await createInvoice(payload);
      }
      
      toast({
        title: isEdit ? "✅ Invoice Updated" : "✅ Invoice Created",
        description: isEdit ? "Invoice has been updated successfully" : "Invoice has been created successfully",
      });
      navigate("/invoices");
    } catch (error) {
      console.error("Error saving invoice:", error);
      toast({
        title: "❌ Error",
        description: "Failed to save invoice. Please try again.",
        variant: "destructive"
      });
    }
  };

  const isSaving = creating || updating;

  // Mock email sending
  const handleSendToClient = async () => {
    const invoiceData = { ...formData, status: InvoiceStatus.PENDING_REVIEW };
    await handleSave(InvoiceStatus.PENDING_REVIEW);
    
    // Simulate email
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    toast({
      title: "📧 Email Sent",
      description: `Invoice emailed to ${invoiceData.to_company?.email || 'client'}`,
    });
  };

  return (
    <DashboardLayout
      title={isEdit ? 'Edit Invoice' : 'Create New Invoice'}
      subtitle="Complete all invoice details below"
      actions={
        <Badge variant="outline" className="text-sm px-3 py-1">
          {existingInvoice?.status || "Draft"}
        </Badge>
      }
      backAction={
        <Button variant="outline" onClick={() => navigate("/invoices")} leadingIcon={<ArrowLeft />}>
          Back to Invoices
        </Button>
      }
    >
      <div className="space-y-6">
        {/* Dispute Alert Banner */}
        {existingInvoice?.status === InvoiceStatus.DISPUTED && disputedIndices.length > 0 && (
          <div className="bg-red-50 border border-red-200 rounded-xl p-4 mb-6">
            <div className="flex items-start gap-3">
              <div className="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0">
                <span className="text-red-700 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>
        )}

        <div>
          {/* Quick Actions - Simplified */}
          {!isEdit && (
            <div className="mb-6 p-4 bg-primary/5 rounded-xl border border-primary/20">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 bg-primary/10 rounded-lg flex items-center justify-center">
                  <Calendar className="w-5 h-5 text-primary" />
                </div>
                <div>
                  <h3 className="font-bold text-primary-text">Import from Event</h3>
                  <p className="text-xs text-muted-text">Quickly fill invoice from a completed event's shifts</p>
                </div>
              </div>
              <Select onValueChange={(val) => {
                const event = events.find(e => e.id === val);
                if (event) handleImportFromEvent(event);
              }}>
                <SelectTrigger className="bg-card border-border/50">
                  <SelectValue placeholder="Select an event to import data..." />
                </SelectTrigger>
                <SelectContent>
                  {events.map(event => (
                    <SelectItem key={event.id} value={event.id}>
                      <div className="flex items-center gap-2">
                        <span className="font-medium">{event.eventName}</span>
                        <span className="text-xs text-muted-foreground">• {event.date ? format(parseISO(event.date as string), 'MMM d, yyyy') : 'No date'}</span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          {/* Client Selection - Top Section */}
          {!isEdit && (
            <div className="mb-6 p-4 bg-muted/20 rounded-xl border border-border/50">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 bg-muted/30 rounded-lg flex items-center justify-center">
                  <Building2 className="w-5 h-5 text-muted-foreground" />
                </div>
                <div>
                  <h3 className="font-bold text-primary-text">Select Client</h3>
                  <p className="text-xs text-muted-text">Choose a client to auto-fill company details and rates</p>
                </div>
              </div>
              <Select value={selectedClientId} onValueChange={handleClientSelect}>
                <SelectTrigger className="bg-card border-border/50">
                  <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.businessName}</span>
                        {business.hubBuilding && (
                          <span className="text-xs text-muted-foreground">• {business.hubBuilding}</span>
                        )}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          {/* Invoice Details Header */}
          <div className="flex flex-col md:flex-row items-start justify-between mb-6 pb-6 border-b border-border/30 gap-6">
            <div className="flex-1 w-full">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-12 h-12 bg-primary/10 rounded-xl flex items-center justify-center">
                  <FileText className="w-6 h-6 text-primary" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-primary-text">Invoice Details</h2>
                  <div className="flex items-center gap-2 text-sm text-secondary-text mt-1">
                    <Calendar className="w-3.5 h-3.5" />
                    <span>Event: {formData.event_name || "Internal Support"}</span>
                  </div>
                </div>
              </div>

              <div className="bg-muted/10 p-4 rounded-xl mb-4 border border-border/30">
                <div className="text-xs text-muted-text font-bold uppercase tracking-wider mb-1">Invoice Number</div>
                <div className="font-bold text-2xl text-primary-text font-mono">{formData.invoice_number}</div>
              </div>

              <div className="grid grid-cols-2 gap-4 mb-4">
                <div>
                  <Label className="text-xs font-bold text-muted-text uppercase">Invoice Date</Label>
                  <Input
                    type="date"
                    value={formData.invoice_date}
                    onChange={(e) => setFormData({ ...formData, invoice_date: e.target.value })}
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label className="text-xs font-bold text-muted-text uppercase">Due Date</Label>
                  <Input
                    type="date"
                    value={formData.due_date}
                    onChange={(e) => setFormData({ ...formData, due_date: e.target.value })}
                    className="mt-1"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4 mb-4">
                <div>
                  <Label className="text-xs font-bold text-muted-text uppercase">Hub</Label>
                  <Input
                    value={formData.hub}
                    onChange={(e) => setFormData({ ...formData, hub: e.target.value })}
                    placeholder="Hub"
                    className="mt-1"
                  />
                </div>
                <div>
                  <Label className="text-xs font-bold text-muted-text uppercase">Manager</Label>
                  <Input
                    value={formData.manager}
                    onChange={(e) => setFormData({ ...formData, manager: e.target.value })}
                    placeholder="Manager Name"
                    className="mt-1"
                  />
                </div>
              </div>

              <div>
                <Label className="text-xs font-bold text-muted-text uppercase">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 w-full md:text-right">
              <div className="mb-4">
                <Label className="text-xs font-bold text-muted-text uppercase block mb-2">Payment Terms</Label>
                <div className="flex gap-2 md:justify-end flex-wrap">
                  {[
                    { label: "30 days", value: "NET_30", days: 30 },
                    { label: "45 days", value: "NET_45", days: 45 },
                    { label: "60 days", value: "NET_60", days: 60 }
                  ].map(term => (
                    <Badge
                      key={term.value}
                      variant="outline"
                      className={`cursor-pointer transition-all border ${formData.payment_terms === term.value ? "bg-primary text-primary-foreground border-primary" : "bg-card hover:bg-muted"}`}
                      onClick={() => setFormData({ 
                        ...formData, 
                        payment_terms: term.value, 
                        due_date: format(addDays(new Date(formData.invoice_date), term.days), 'yyyy-MM-dd') 
                      })}
                    >
                      {term.label}
                    </Badge>
                  ))}
                </div>
              </div>

              <div className="mt-4 md:mt-10 space-y-3">
                <div className="flex flex-col md:flex-row items-center gap-2 md:justify-end">
                  <span className="text-sm text-secondary-text w-full md:w-auto text-left">Department:</span>
                  <Input
                    value={formData.department}
                    onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                    placeholder="Dept Code"
                    className="h-9 w-full md:w-48"
                  />
                </div>
                <div className="flex flex-col md:flex-row items-center gap-2 md:justify-end">
                  <span className="text-sm text-secondary-text w-full md:w-auto text-left">PO#:</span>
                  <Input
                    value={formData.po_reference}
                    onChange={(e) => setFormData({ ...formData, po_reference: e.target.value })}
                    placeholder="PO Number"
                    className="h-9 w-full md:w-48"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* From and To - Compact */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            {/* From Company */}
            <div className="bg-muted/5 p-4 rounded-xl border border-border/50">
              <div className="flex items-center gap-2 mb-3 pb-2 border-b border-border/30">
                <div className="w-6 h-6 bg-primary/10 rounded flex items-center justify-center text-primary text-xs font-bold">F</div>
                <span className="text-xs font-bold text-primary-text uppercase tracking-wider">From (Vendor)</span>
              </div>
              {/* Inputs for from_company */}
              <div className="space-y-2">
                {['name', 'address', 'phone', 'email'].map(field => (
                  <div key={field} className="relative group">
                    <input
                      value={formData.from_company[field]}
                      onChange={(e) => setFormData({ ...formData, from_company: { ...formData.from_company, [field]: e.target.value } })}
                      className="w-full text-sm font-medium text-primary-text bg-transparent border-0 border-b border-transparent hover:border-border focus:border-primary focus:ring-0 px-0 py-1 transition-all placeholder:text-muted-foreground/50"
                      placeholder={field.charAt(0).toUpperCase() + field.slice(1)}
                    />
                    {field === 'email' && <Mail className="absolute right-0 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />}
                    {field === 'phone' && <Phone className="absolute right-0 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />}
                  </div>
                ))}
              </div>
            </div>

            {/* To Company */}
            <div className="bg-muted/5 p-4 rounded-xl border border-border/50">
              <div className="flex items-center gap-2 mb-3 pb-2 border-b border-border/30">
                <div className="w-6 h-6 bg-secondary text-secondary-foreground rounded flex items-center justify-center text-xs font-bold">T</div>
                <span className="text-xs font-bold text-primary-text uppercase tracking-wider">To (Client)</span>
              </div>
              <div className="space-y-2">
                {['name', 'hub_name', 'department', 'po_reference', 'address', 'phone', 'email'].map(field => (
                  <div key={field} className="relative group">
                    <input
                      value={field === 'department' || field === 'po_reference' ? formData[field] : formData.to_company[field]}
                      onChange={(e) => {
                        if (field === 'department' || field === 'po_reference') {
                          setFormData({ ...formData, [field]: e.target.value });
                        } else {
                          setFormData({ ...formData, to_company: { ...formData.to_company, [field]: e.target.value } });
                        }
                      }}
                      placeholder={field.replace('_', ' ').charAt(0).toUpperCase() + field.slice(1)}
                      className="w-full text-sm text-secondary-text bg-transparent border-0 border-b border-transparent hover:border-border focus:border-primary focus:ring-0 px-0 py-1 transition-all placeholder:text-muted-foreground/50"
                    />
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Staff Table */}
          <div className="mb-8">
            <div className="flex items-center justify-between mb-4 p-4 bg-muted/10 rounded-xl border border-border/30">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center border border-border/30 shadow-sm">
                  <User className="w-5 h-5 text-primary" />
                </div>
                <div>
                  <h3 className="font-bold text-primary-text">Staff Entries</h3>
                  <p className="text-xs text-muted-text">{formData.staff_entries.length} entries</p>
                </div>
              </div>
              <Button size="sm" onClick={handleAddStaffEntry} variant="outline" className="border-dashed border-border hover:border-primary hover:bg-primary/5">
                <Plus className="w-4 h-4 mr-1" />
                Add Staff Entry
              </Button>
            </div>

            <Card className="border-border/50 shadow-sm overflow-hidden">
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/30 border-b border-border/50">
                      <TableHead className="w-10 text-[10px] uppercase font-bold text-muted-text">#</TableHead>
                      <TableHead className="w-32 text-[10px] uppercase font-bold text-muted-text">Name</TableHead>
                      <TableHead className="w-28 text-[10px] uppercase font-bold text-muted-text">Position</TableHead>
                      <TableHead className="w-24 text-[10px] uppercase font-bold text-muted-text">ClockIn</TableHead>
                      <TableHead className="w-16 text-[10px] uppercase font-bold text-muted-text">Lunch</TableHead>
                      <TableHead className="w-24 text-[10px] uppercase font-bold text-muted-text">Checkout</TableHead>
                      <TableHead className="w-16 text-[10px] uppercase font-bold text-muted-text">Wrkd</TableHead>
                      <TableHead className="w-14 text-[10px] uppercase font-bold text-muted-text">Reg</TableHead>
                      <TableHead className="w-14 text-[10px] uppercase font-bold text-muted-text">OT</TableHead>
                      <TableHead className="w-14 text-[10px] uppercase font-bold text-muted-text">DT</TableHead>
                      <TableHead className="w-16 text-[10px] uppercase font-bold text-muted-text">Rate</TableHead>
                      <TableHead className="w-16 text-right text-[10px] uppercase font-bold text-muted-text">Reg$</TableHead>
                      <TableHead className="w-16 text-right text-[10px] uppercase font-bold text-muted-text">OT$</TableHead>
                      <TableHead className="w-16 text-right text-[10px] uppercase font-bold text-muted-text">DT$</TableHead>
                      <TableHead className="w-20 text-right text-[10px] uppercase font-bold text-muted-text">Total</TableHead>
                      <TableHead className="w-10 text-[10px] uppercase font-bold text-muted-text"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {formData.staff_entries.map((entry: any, idx: number) => (
                      <TableRow key={idx} className={`hover:bg-muted/10 ${disputedIndices.includes(idx) ? 'bg-red-50/50 border-l-2 border-l-red-500' : ''}`}>
                        <TableCell className="text-xs font-medium text-muted-text">{idx + 1}</TableCell>
                        <TableCell>
                          <Popover>
                            <PopoverTrigger asChild>
                              <Button variant="outline" size="sm" className="h-8 w-full justify-start font-normal truncate text-xs px-2 border-dashed border-border/60">
                                {entry.name || <span className="text-muted-foreground">Select</span>}
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-64 p-2" align="start">
                              <Input
                                placeholder="Search staff..."
                                className="mb-2 h-8"
                                onChange={(_) => { }}
                              />
                              <div className="max-h-48 overflow-y-auto space-y-1">
                                {staffDirectory.map(staff => (
                                  <button
                                    key={staff.id}
                                    onClick={() => handleStaffChange(idx, 'name', staff.fullName)}
                                    className="w-full text-left px-2 py-1.5 text-xs rounded hover:bg-muted transition-colors"
                                  >
                                    <span className="font-medium">{staff.fullName}</span>
                                    {staff.role && <span className="text-[10px] text-muted-foreground ml-1 bg-muted px-1 rounded">• {staff.role}</span>}
                                  </button>
                                ))}
                              </div>
                            </PopoverContent>
                          </Popover>
                        </TableCell>
                        <TableCell>
                          <Select
                            value={entry.position || ""}
                            onValueChange={(val: string) => handlePositionChange(idx, val)}
                          >
                            <SelectTrigger className="h-8 w-full text-xs border-border/60">
                              <SelectValue placeholder="Position" />
                            </SelectTrigger>
                            <SelectContent>
                              {["Line Cook", "Prep Cook", "Sous Chef", "Executive Chef", "Server", "Bartender", "Barback", "Host", "Busser", "Dishwasher", "Food Runner", "Catering Staff", "Event Staff", "Supervisor", "Manager"].map(pos => (
                                <SelectItem key={pos} value={pos} className="text-xs">{pos}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </TableCell>
                        <TableCell>
                          <Popover open={timePickerOpen === `checkin-${idx}`} onOpenChange={(open) => setTimePickerOpen(open ? `checkin-${idx}` : null)}>
                            <PopoverTrigger asChild>
                              <Button variant="outline" size="sm" className="h-8 w-full justify-start font-normal text-xs px-2 border-border/60">
                                <Clock className="w-3 h-3 mr-1.5 text-muted-foreground" />
                                {entry.check_in}
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-52 p-3" align="start">
                              <div className="space-y-3">
                                <div className="flex gap-1">
                                  <Select value={selectedTime.hours} onValueChange={(val: string) => setSelectedTime({ ...selectedTime, hours: val })}>
                                    <SelectTrigger><SelectValue /></SelectTrigger>
                                    <SelectContent>{Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0')).map(h => <SelectItem key={h} value={h}>{h}</SelectItem>)}</SelectContent>
                                  </Select>
                                  <Select value={selectedTime.minutes} onValueChange={(val: string) => setSelectedTime({ ...selectedTime, minutes: val })}>
                                    <SelectTrigger><SelectValue /></SelectTrigger>
                                    <SelectContent>{['00', '15', '30', '45'].map(m => <SelectItem key={m} value={m}>{m}</SelectItem>)}</SelectContent>
                                  </Select>
                                  <div className="flex gap-0.5">
                                    {['AM', 'PM'].map(p => (
                                      <button key={p} onClick={() => setSelectedTime({ ...selectedTime, period: p })} className={`px-2 text-xs rounded ${selectedTime.period === p ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>{p}</button>
                                    ))}
                                  </div>
                                </div>
                                <Button size="sm" onClick={() => handleTimeSelect(idx, 'check_in')} className="w-full">Set</Button>
                              </div>
                            </PopoverContent>
                          </Popover>
                        </TableCell>
                        <TableCell>
                          <Select
                            value={entry.lunch === "NB" ? "NB" : String(entry.lunch || 0)}
                            onValueChange={(val: string) => handleStaffChange(idx, 'lunch', val === "NB" ? "NB" : parseInt(val))}
                          >
                            <SelectTrigger className="h-8 w-full text-xs border-border/60">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="NB">NB</SelectItem>
                              {[5, 10, 15, 20, 25, 30, 45, 60].map(m => <SelectItem key={m} value={String(m)}>{m}</SelectItem>)}
                            </SelectContent>
                          </Select>
                        </TableCell>
                        <TableCell>
                          <Popover open={timePickerOpen === `checkout-${idx}`} onOpenChange={(open) => setTimePickerOpen(open ? `checkout-${idx}` : null)}>
                            <PopoverTrigger asChild>
                              <Button variant="outline" size="sm" className="h-8 w-full justify-start font-normal text-xs px-2 border-border/60">
                                <Clock className="w-3 h-3 mr-1.5 text-muted-foreground" />
                                {entry.check_out || "hh:mm"}
                              </Button>
                            </PopoverTrigger>
                            <PopoverContent className="w-52 p-3" align="start">
                              <div className="space-y-3">
                                <div className="flex gap-1">
                                  <Select value={selectedTime.hours} onValueChange={(val: string) => setSelectedTime({ ...selectedTime, hours: val })}>
                                    <SelectTrigger><SelectValue /></SelectTrigger>
                                    <SelectContent>{Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0')).map(h => <SelectItem key={h} value={h}>{h}</SelectItem>)}</SelectContent>
                                  </Select>
                                  <Select value={selectedTime.minutes} onValueChange={(val: string) => setSelectedTime({ ...selectedTime, minutes: val })}>
                                    <SelectTrigger><SelectValue /></SelectTrigger>
                                    <SelectContent>{['00', '15', '30', '45'].map(m => <SelectItem key={m} value={m}>{m}</SelectItem>)}</SelectContent>
                                  </Select>
                                  <div className="flex gap-0.5">
                                    {['AM', 'PM'].map(p => (
                                      <button key={p} onClick={() => setSelectedTime({ ...selectedTime, period: p })} className={`px-2 text-xs rounded ${selectedTime.period === p ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>{p}</button>
                                    ))}
                                  </div>
                                </div>
                                <Button size="sm" onClick={() => handleTimeSelect(idx, 'check_out')} className="w-full">Set</Button>
                              </div>
                            </PopoverContent>
                          </Popover>
                        </TableCell>
                        <TableCell>
                          <Input type="number" step="0.1" value={entry.worked_hours} onChange={(e) => handleStaffChange(idx, 'worked_hours', parseFloat(e.target.value))} className="h-8 w-14 text-xs px-1 text-center font-medium bg-muted/20 border-0" />
                        </TableCell>
                        <TableCell>
                          <Input type="number" step="0.1" value={entry.regular_hours} onChange={(e) => handleStaffChange(idx, 'regular_hours', parseFloat(e.target.value))} className="h-8 w-12 text-xs px-1 text-center" />
                        </TableCell>
                        <TableCell>
                          <Input type="number" step="0.1" value={entry.ot_hours} onChange={(e) => handleStaffChange(idx, 'ot_hours', parseFloat(e.target.value))} className="h-8 w-12 text-xs px-1 text-center" />
                        </TableCell>
                        <TableCell>
                          <Input type="number" step="0.1" value={entry.dt_hours} onChange={(e) => handleStaffChange(idx, 'dt_hours', parseFloat(e.target.value))} className="h-8 w-12 text-xs px-1 text-center" />
                        </TableCell>
                        <TableCell>
                          <Input type="number" step="0.01" value={entry.rate} onChange={(e) => handleStaffChange(idx, 'rate', parseFloat(e.target.value))} className="h-8 w-14 text-xs px-1 text-right" />
                        </TableCell>
                        <TableCell className="text-right text-xs text-muted-text font-mono">${entry.regular_value?.toFixed(0) || "0"}</TableCell>
                        <TableCell className="text-right text-xs text-muted-text font-mono">${entry.ot_value?.toFixed(0) || "0"}</TableCell>
                        <TableCell className="text-right text-xs text-muted-text font-mono">${entry.dt_value?.toFixed(0) || "0"}</TableCell>
                        <TableCell className="text-right font-bold text-xs text-primary-text font-mono">${entry.total?.toFixed(2) || "0"}</TableCell>
                        <TableCell className="text-center">
                          <Button variant="ghost" size="sm" onClick={() => handleRemoveStaff(idx)} className="h-6 w-6 p-0 text-muted-foreground hover:text-red-500 hover:bg-red-50">
                            <Trash2 className="w-3.5 h-3.5" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </Card>
          </div>

          {/* Charges */}
          <div className="mb-6">
            <div className="flex items-center justify-between mb-4 p-4 bg-muted/10 rounded-xl border border-border/30">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center border border-border/30 shadow-sm">
                  <span className="text-lg">💰</span>
                </div>
                <div>
                  <h3 className="font-bold text-primary-text">Additional Charges</h3>
                  <p className="text-xs text-muted-text">{formData.charges.length} charges</p>
                </div>
              </div>
              <Button size="sm" onClick={handleAddCharge} variant="outline" className="border-dashed border-border hover:border-primary hover:bg-primary/5">
                <Plus className="w-4 h-4 mr-1" />
                Add Charge
              </Button>
            </div>

            <Card className="border-border/50 shadow-sm overflow-hidden">
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/30 border-b border-border/50">
                      <TableHead className="w-12 text-[10px] uppercase font-bold text-muted-text">#</TableHead>
                      <TableHead className="text-[10px] uppercase font-bold text-muted-text">Name</TableHead>
                      <TableHead className="w-24 text-[10px] uppercase font-bold text-muted-text">QTY</TableHead>
                      <TableHead className="w-32 text-[10px] uppercase font-bold text-muted-text">Rate</TableHead>
                      <TableHead className="w-32 text-[10px] uppercase font-bold text-muted-text">Price</TableHead>
                      <TableHead className="w-16 text-[10px] uppercase font-bold text-muted-text">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {formData.charges.map((charge: any, idx: number) => (
                      <TableRow key={idx} className="hover:bg-muted/10">
                        <TableCell className="text-xs font-medium text-muted-text">{idx + 1}</TableCell>
                        <TableCell>
                          <Input value={charge.name} onChange={(e) => handleChargeChange(idx, 'name', e.target.value)} className="h-8 max-w-md" />
                        </TableCell>
                        <TableCell>
                          <Input type="number" step="0.01" value={charge.qty} onChange={(e) => handleChargeChange(idx, 'qty', parseFloat(e.target.value))} className="h-8 w-20" />
                        </TableCell>
                        <TableCell>
                          <Input type="number" step="0.01" value={charge.rate} onChange={(e) => handleChargeChange(idx, 'rate', parseFloat(e.target.value))} className="h-8 w-24" />
                        </TableCell>
                        <TableCell className="font-mono font-bold text-sm text-primary-text">${charge.price?.toFixed(2) || "0.00"}</TableCell>
                        <TableCell className="text-center">
                          <Button variant="ghost" size="sm" onClick={() => handleRemoveCharge(idx)} className="h-8 w-8 p-0 text-muted-foreground hover:text-red-500 hover:bg-red-50">
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </Card>
          </div>

          {/* Totals */}
          <div className="flex justify-end mb-6">
            <div className="w-full md:w-96 bg-muted/5 p-6 rounded-xl border border-border/50">
              <div className="space-y-4">
                <div className="flex justify-between text-sm">
                  <span className="text-secondary-text">Sub total:</span>
                  <span className="font-semibold text-primary-text font-mono">${totals.subtotal.toFixed(2)}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-secondary-text">Other charges:</span>
                  <Input type="number" step="0.01" value={formData.other_charges} onChange={(e) => setFormData({ ...formData, other_charges: e.target.value })} className="h-8 w-32 text-right bg-white" />
                </div>
                <div className="flex justify-between text-xl font-bold pt-4 border-t border-border/30">
                  <span className="text-primary-text">Grand total:</span>
                  <span className="text-primary font-mono">${totals.grandTotal.toFixed(2)}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Notes */}
          <div className="mb-8">
            <Label className="mb-2 block text-xs font-bold text-muted-text uppercase">Notes</Label>
            <Textarea value={formData.notes} onChange={(e) => setFormData({ ...formData, notes: e.target.value })} placeholder="Enter your notes here..." rows={3} className="resize-none" />
          </div>

          {/* Actions */}
          <div className="flex justify-between items-center pt-6 border-t border-border/30">
            <Button variant="outline" onClick={() => navigate("/invoices")} className="border-border">
              Cancel
            </Button>
            <div className="flex gap-3">
              <Button
                variant="outline"
                onClick={() => handleSave("DRAFT")}
                disabled={isSaving}
                className="text-primary hover:text-primary hover:bg-primary/5"
              >
                Save as Draft
              </Button>
              <Button
                variant="secondary"
                onClick={() => handleSave()}
                disabled={isSaving}
                className="bg-secondary text-secondary-foreground hover:bg-secondary/80"
              >
                {isSaving ? "Saving..." : isEdit ? "Update Invoice" : "Create Invoice"}
              </Button>
              <Button
                onClick={handleSendToClient}
                disabled={isSaving}
                className="bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm"
              >
                {isSaving ? "Sending..." : "Send to Client"}
              </Button>
            </div>
          </div>
        </div>
      </div>
    </DashboardLayout>
  );
}