import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/components/ui/use-toast";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Printer, Flag, CheckCircle, MoreVertical, FileText, Edit, CreditCard, Save, X, Pencil, Eye, Trash2, AlertTriangle, Plus, ChevronDown
} from "lucide-react";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { format, parseISO } from "date-fns";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";

const statusColors = {
  'Draft': 'bg-slate-500',
  'Pending Review': 'bg-amber-500',
  'Approved': 'bg-green-500',
  'Disputed': 'bg-red-500',
  'Under Review': 'bg-orange-500',
  'Resolved': 'bg-blue-500',
  'Overdue': 'bg-red-600',
  'Paid': 'bg-emerald-500',
  'Reconciled': 'bg-purple-500',
  'Cancelled': 'bg-slate-400',
};

export default function InvoiceDetailView({ invoice, userRole, onClose }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const [showDisputeDialog, setShowDisputeDialog] = useState(false);
  const [disputeReason, setDisputeReason] = useState("");
  const [disputeDetails, setDisputeDetails] = useState("");
  const [selectedItems, setSelectedItems] = useState([]);
  const [isEditingDetails, setIsEditingDetails] = useState(false);
  const [editingEntryIndex, setEditingEntryIndex] = useState(null);
  const [editedEntry, setEditedEntry] = useState(null);
  const [expandedPositions, setExpandedPositions] = useState({});
  const [editedDetails, setEditedDetails] = useState({
    event_name: "",
    po_reference: "",
    event_date: "",
    due_date: "",
    from_company: { name: "", address: "", email: "", phone: "" },
    to_company: { name: "", address: "", email: "", manager: "", phone: "", vendor_id: "" }
  });

  // Initialize edited details when invoice changes
  useEffect(() => {
    if (invoice) {
      setEditedDetails({
        event_name: invoice.event_name || "",
        po_reference: invoice.po_reference || "",
        event_date: invoice.event_date || "",
        due_date: invoice.due_date || "",
        from_company: {
          name: invoice.from_company?.name || invoice.vendor_name || "",
          address: invoice.from_company?.address || "",
          email: invoice.from_company?.email || "",
          phone: invoice.from_company?.phone || ""
        },
        to_company: {
          name: invoice.to_company?.name || invoice.business_name || "",
          address: invoice.to_company?.address || "",
          email: invoice.to_company?.email || "",
          manager: invoice.to_company?.manager || invoice.manager_name || "",
          phone: invoice.to_company?.phone || "",
          vendor_id: invoice.to_company?.vendor_id || ""
        }
      });
    }
  }, [invoice]);

  const updateInvoiceMutation = useMutation({
    mutationFn: ({ id, data }) => base44.entities.Invoice.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['invoices'] });
      toast({
        title: "✅ Invoice Updated",
        description: "Invoice has been updated successfully",
      });
      if (onClose) onClose();
    },
  });

  const handleApprove = async () => {
    const user = await base44.auth.me();
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        status: "Approved",
        approved_by: user.email,
        approved_date: new Date().toISOString(),
      }
    });
  };

  const handleMarkPaid = async () => {
    const user = await base44.auth.me();
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        status: "Paid",
        paid_date: new Date().toISOString().split('T')[0],
        payment_method: "Credit Card",
        payment_reference: `PAY-${Date.now()}`,
      }
    });
  };

  const handleEditInvoice = () => {
    const disputedIndices = invoice.disputed_items?.map(item => item.staff_index).join(',') || '';
    navigate(createPageUrl(`InvoiceEditor?id=${invoice.id}&disputed=${disputedIndices}`));
  };

  const handleDispute = async () => {
    const user = await base44.auth.me();
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        status: "Disputed",
        dispute_reason: disputeReason,
        dispute_details: disputeDetails,
        disputed_items: selectedItems,
        disputed_by: user.email,
        disputed_date: new Date().toISOString(),
      }
    });
    setShowDisputeDialog(false);
  };

  const handlePrint = () => {
    window.print();
  };

  const handleSaveDetails = () => {
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        event_name: editedDetails.event_name,
        po_reference: editedDetails.po_reference,
        event_date: editedDetails.event_date,
        due_date: editedDetails.due_date,
        from_company: editedDetails.from_company,
        to_company: editedDetails.to_company,
        business_name: editedDetails.to_company.name,
        manager_name: editedDetails.to_company.manager,
        vendor_name: editedDetails.from_company.name,
      }
    });
    setIsEditingDetails(false);
  };

  const handleCancelEdit = () => {
    setEditedDetails({
      event_name: invoice.event_name || "",
      po_reference: invoice.po_reference || "",
      event_date: invoice.event_date || "",
      due_date: invoice.due_date || "",
      from_company: {
        name: invoice.from_company?.name || invoice.vendor_name || "",
        address: invoice.from_company?.address || "",
        email: invoice.from_company?.email || "",
        phone: invoice.from_company?.phone || ""
      },
      to_company: {
        name: invoice.to_company?.name || invoice.business_name || "",
        address: invoice.to_company?.address || "",
        email: invoice.to_company?.email || "",
        manager: invoice.to_company?.manager || invoice.manager_name || "",
        phone: invoice.to_company?.phone || "",
        vendor_id: invoice.to_company?.vendor_id || ""
      }
    });
    setIsEditingDetails(false);
  };

  const handleEditEntry = (roleIdx, entryIdx, entry) => {
    setEditingEntryIndex({ roleIdx, entryIdx });
    setEditedEntry({ ...entry });
  };

  const handleSaveEntry = () => {
    if (!editingEntryIndex || !editedEntry) return;
    
    const updatedRoles = [...(invoice.roles || displayRoles)];
    if (updatedRoles[editingEntryIndex.roleIdx]?.staff_entries) {
      updatedRoles[editingEntryIndex.roleIdx].staff_entries[editingEntryIndex.entryIdx] = editedEntry;
      updatedRoles[editingEntryIndex.roleIdx].role_subtotal = updatedRoles[editingEntryIndex.roleIdx].staff_entries.reduce(
        (sum, e) => sum + (e.total || 0), 0
      );
    }
    
    const newSubtotal = updatedRoles.reduce((sum, r) => sum + (r.role_subtotal || 0), 0);
    const newAmount = newSubtotal + (invoice.other_charges || 0);
    
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        roles: updatedRoles,
        subtotal: newSubtotal,
        amount: newAmount
      }
    });
    setEditingEntryIndex(null);
    setEditedEntry(null);
  };

  const handleRemoveEntry = (roleIdx, entryIdx) => {
    const updatedRoles = [...(invoice.roles || displayRoles)];
    if (updatedRoles[roleIdx]?.staff_entries) {
      updatedRoles[roleIdx].staff_entries.splice(entryIdx, 1);
      updatedRoles[roleIdx].role_subtotal = updatedRoles[roleIdx].staff_entries.reduce(
        (sum, e) => sum + (e.total || 0), 0
      );
    }
    
    const newSubtotal = updatedRoles.reduce((sum, r) => sum + (r.role_subtotal || 0), 0);
    const newAmount = newSubtotal + (invoice.other_charges || 0);
    
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: {
        roles: updatedRoles,
        subtotal: newSubtotal,
        amount: newAmount
      }
    });
  };

  const handleAddEntry = () => {
    const newEntry = {
      staff_name: "",
      date: new Date().toISOString().split('T')[0],
      position: "",
      check_in: "",
      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 updatedRoles = [...(invoice.roles || displayRoles)];
    if (updatedRoles.length === 0) {
      updatedRoles.push({ role_name: "Staff", staff_entries: [], role_subtotal: 0 });
    }
    updatedRoles[0].staff_entries.push(newEntry);
    
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: { roles: updatedRoles }
    });
    
    // Start editing the new entry
    setTimeout(() => {
      setEditingEntryIndex({ roleIdx: 0, entryIdx: updatedRoles[0].staff_entries.length - 1 });
      setEditedEntry(newEntry);
    }, 100);
  };

  const handleFlagEntry = async (roleIdx, entryIdx, entry) => {
    const user = await base44.auth.me();
    const flaggedItems = [...(invoice.disputed_items || [])];
    const existingIndex = flaggedItems.findIndex(item => item.role_index === roleIdx && item.staff_index === entryIdx);
    
    if (existingIndex === -1) {
      // Add flag with details
      flaggedItems.push({ 
        role_index: roleIdx, 
        staff_index: entryIdx,
        staff_name: entry?.staff_name || entry?.name || 'Unknown',
        position: entry?.position || 'Unknown',
        flagged_by: user.email,
        flagged_by_role: user.user_role || user.role,
        flagged_at: new Date().toISOString(),
        worked_hours: entry?.worked_hours,
        total: entry?.total
      });
    } else {
      // Remove flag if already flagged (toggle)
      flaggedItems.splice(existingIndex, 1);
    }
    
    updateInvoiceMutation.mutate({
      id: invoice.id,
      data: { disputed_items: flaggedItems }
    });
  };

  const parseTimeToMinutes = (timeStr) => {
    if (!timeStr || timeStr === "hh:mm" || timeStr === "—") return null;
    
    // Try format: "06:00 AM" or "02:30 PM"
    let match = timeStr.match(/(\d{1,2}):(\d{2})\s*(AM|PM)/i);
    if (match) {
      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;
    }
    
    // Try 24-hour format: "06:00" or "14:30"
    match = timeStr.match(/(\d{1,2}):(\d{2})/);
    if (match) {
      const hours = parseInt(match[1]);
      const minutes = parseInt(match[2]);
      return hours * 60 + minutes;
    }
    
    return null;
  };

  const recalculateEntry = (entry) => {
    // Calculate worked hours from check_in and check_out
    let workedHours = entry.worked_hours || 0;
    let nbBonusHour = 0;
    const startMinutes = parseTimeToMinutes(entry.check_in);
    const endMinutes = parseTimeToMinutes(entry.check_out);
    
    if (startMinutes !== null && endMinutes !== null) {
      let totalMinutes = endMinutes - startMinutes;
      if (totalMinutes < 0) totalMinutes += 24 * 60; // Handle overnight shifts
      
      // NB = No Break, adds 1 extra REGULAR hour (not OT)
      // Other breaks >= 20 minutes are deducted
      const lunchVal = entry.lunch;
      if (lunchVal === "NB") {
        nbBonusHour = 1; // NB adds 1 extra regular hour
      } else {
        const lunchMinutes = (lunchVal === 0 || lunchVal === "0") ? 0 : 
                             (typeof lunchVal === 'number' && lunchVal >= 20) ? lunchVal :
                             (typeof lunchVal === 'string' && parseInt(lunchVal) >= 20) ? parseInt(lunchVal) : 0;
        totalMinutes -= lunchMinutes;
      }
      workedHours = Math.max(0, totalMinutes / 60);
    }

    // Actual consecutive hours worked (without NB bonus) determines OT/DT
    const consecutiveHours = workedHours;
    
    // Distribute hours: first 8 regular, next 4 OT, rest DT (based on consecutive hours)
    let regularHours = 0, otHours = 0, dtHours = 0;
    if (consecutiveHours <= 8) {
      regularHours = consecutiveHours;
    } else if (consecutiveHours <= 12) {
      regularHours = 8;
      otHours = consecutiveHours - 8;
    } else {
      regularHours = 8;
      otHours = 4;
      dtHours = consecutiveHours - 12;
    }
    
    // Add NB bonus to regular hours only
    regularHours += nbBonusHour;
    workedHours += nbBonusHour;

    const rate = parseFloat(entry.rate) || 0;
    const regValue = regularHours * rate;
    const otValue = otHours * rate * 1.5;
    const dtValue = dtHours * rate * 2;
    
    return {
      ...entry,
      worked_hours: parseFloat(workedHours.toFixed(2)),
      regular_hours: parseFloat(regularHours.toFixed(2)),
      ot_hours: parseFloat(otHours.toFixed(2)),
      dt_hours: parseFloat(dtHours.toFixed(2)),
      regular_value: parseFloat(regValue.toFixed(2)),
      ot_value: parseFloat(otValue.toFixed(2)),
      dt_value: parseFloat(dtValue.toFixed(2)),
      total: parseFloat((regValue + otValue + dtValue).toFixed(2))
    };
  };

  const toggleItemSelection = (roleIndex, staffIndex) => {
    const itemId = { role_index: roleIndex, staff_index: staffIndex };
    setSelectedItems(prev => {
      const exists = prev.some(item => item.role_index === roleIndex && item.staff_index === staffIndex);
      if (exists) {
        return prev.filter(item => !(item.role_index === roleIndex && item.staff_index === staffIndex));
      }
      return [...prev, itemId];
    });
  };

  if (!invoice) return null;

  // Generate demo staff entries if none exist
  const demoStaffEntries = [
    { staff_name: "Maria Garcia", date: invoice.issue_date || "2025-10-15", position: "Bartender", check_in: "09:00 AM", check_out: "05:00 PM", worked_hours: 8, regular_hours: 8, ot_hours: 0, dt_hours: 0, rate: 52.68, regular_value: 421.44, ot_value: 0, dt_value: 0, total: 421.44 },
    { staff_name: "Carlos Rodriguez", date: invoice.issue_date || "2025-10-15", position: "Server", check_in: "10:00 AM", check_out: "06:30 PM", worked_hours: 8.5, regular_hours: 8, ot_hours: 0.5, dt_hours: 0, rate: 45.00, regular_value: 360.00, ot_value: 33.75, dt_value: 0, total: 393.75 },
    { staff_name: "Ana Martinez", date: invoice.issue_date || "2025-10-15", position: "Line Cook", check_in: "07:00 AM", check_out: "04:00 PM", worked_hours: 9, regular_hours: 8, ot_hours: 1, dt_hours: 0, rate: 48.50, regular_value: 388.00, ot_value: 72.75, dt_value: 0, total: 460.75 },
  ];

  const demoRoles = [{
    role_name: "Mixed",
    staff_entries: demoStaffEntries,
    role_subtotal: demoStaffEntries.reduce((sum, e) => sum + e.total, 0)
  }];

  // Use real roles if available, otherwise use demo data
  const displayRoles = (invoice.roles && invoice.roles.length > 0 && invoice.roles[0]?.staff_entries?.length > 0) 
    ? invoice.roles 
    : demoRoles;

  // Group entries by position for collapsible view
  const getGroupedByPosition = (staffEntries) => {
    const groups = {};
    staffEntries.forEach((entry, idx) => {
      const position = entry.position || 'Other';
      if (!groups[position]) {
        groups[position] = {
          position,
          entries: [],
          totalWorkedHours: 0,
          totalRegularHours: 0,
          totalOtHours: 0,
          totalDtHours: 0,
          totalRegularValue: 0,
          totalOtValue: 0,
          totalDtValue: 0,
          total: 0
        };
      }
      groups[position].entries.push({ ...entry, originalIndex: idx });
      groups[position].totalWorkedHours += entry.worked_hours || 0;
      groups[position].totalRegularHours += entry.regular_hours || 0;
      groups[position].totalOtHours += entry.ot_hours || 0;
      groups[position].totalDtHours += entry.dt_hours || 0;
      groups[position].totalRegularValue += entry.regular_value || 0;
      groups[position].totalOtValue += entry.ot_value || 0;
      groups[position].totalDtValue += entry.dt_value || 0;
      groups[position].total += entry.total || 0;
    });
    return Object.values(groups);
  };

  const togglePositionExpand = (roleIdx, position) => {
    const key = `${roleIdx}-${position}`;
    setExpandedPositions(prev => ({ ...prev, [key]: !prev[key] }));
  };

  const displaySubtotal = invoice.subtotal || displayRoles.reduce((sum, r) => sum + (r.role_subtotal || 0), 0);
  const displayAmount = invoice.amount || (displaySubtotal + (invoice.other_charges || 0));

  const isClient = userRole === "client";
  const isVendor = userRole === "vendor";
  const isAdmin = userRole === "admin";
  const canEdit = isVendor || isAdmin;
  const canApprove = (isClient || isAdmin) && invoice.status === "Pending Review";
  const canPay = (isClient || isAdmin) && invoice.status === "Approved";
  const canDispute = (isClient || isAdmin) && ["Pending Review", "Approved"].includes(invoice.status);
  const canFlag = isClient || isAdmin;

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
      <div className="max-w-7xl mx-auto p-6">
        {/* Header */}
        <div className="bg-white rounded-2xl shadow-sm border border-slate-200 p-6 mb-6">
          <div className="flex items-start justify-between mb-4">
            <div className="flex items-center gap-4">
              <FileText className="w-8 h-8 text-[#0A39DF]" />
              <div>
                <h1 className="text-3xl font-bold text-slate-900">{invoice.invoice_number}</h1>
                <Badge className={`${statusColors[invoice.status]} text-white px-3 py-1 mt-2`}>
                  {invoice.status}
                </Badge>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button variant="outline" onClick={handlePrint}>
                <Printer className="w-4 h-4 mr-2" />
                Print
              </Button>
              {canEdit && (
                <Button variant="outline" className="text-blue-600 border-blue-200 hover:bg-blue-50" onClick={handleEditInvoice}>
                  <Edit className="w-4 h-4 mr-2" />
                  Edit Invoice
                </Button>
              )}
              {canDispute && (
                <Button variant="outline" className="text-red-600 border-red-200 hover:bg-red-50" onClick={() => setShowDisputeDialog(true)}>
                  <Flag className="w-4 h-4 mr-2" />
                  Dispute Invoice
                </Button>
              )}
              {canApprove && (
                <Button className="bg-green-600 hover:bg-green-700" onClick={handleApprove}>
                  <CheckCircle className="w-4 h-4 mr-2" />
                  Approve Invoice
                </Button>
              )}
              {canPay && (
                <Button className="bg-[#0A39DF] hover:bg-[#0831b8]" onClick={handleMarkPaid}>
                  <CreditCard className="w-4 h-4 mr-2" />
                  Mark as Paid
                </Button>
              )}
            </div>
          </div>

          {/* Event Info */}
          {isEditingDetails ? (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div>
                <Label className="text-xs text-slate-500">Event Name</Label>
                <Input
                  value={editedDetails.event_name}
                  onChange={(e) => setEditedDetails({ ...editedDetails, event_name: e.target.value })}
                  className="h-8 mt-1"
                />
              </div>
              <div>
                <Label className="text-xs text-slate-500">PO#</Label>
                <Input
                  value={editedDetails.po_reference}
                  onChange={(e) => setEditedDetails({ ...editedDetails, po_reference: e.target.value })}
                  className="h-8 mt-1"
                />
              </div>
              <div>
                <Label className="text-xs text-slate-500">Date</Label>
                <Input
                  type="date"
                  value={editedDetails.event_date}
                  onChange={(e) => setEditedDetails({ ...editedDetails, event_date: e.target.value })}
                  className="h-8 mt-1"
                />
              </div>
              <div>
                <Label className="text-xs text-slate-500">Due Date</Label>
                <Input
                  type="date"
                  value={editedDetails.due_date}
                  onChange={(e) => setEditedDetails({ ...editedDetails, due_date: e.target.value })}
                  className="h-8 mt-1"
                />
              </div>
            </div>
          ) : (
            <div className="flex flex-wrap gap-6 text-sm text-slate-600">
              <div>
                <span className="font-semibold">Event Name:</span> {invoice.event_name}
              </div>
              <div>
                <span className="font-semibold">PO#:</span> {invoice.po_reference || "N/A"}
              </div>
              <div>
                <span className="font-semibold">Date:</span> {invoice.event_date ? format(parseISO(invoice.event_date), 'M.d.yyyy') : '—'}
              </div>
              <div>
                <span className="font-semibold">Due date:</span> <span className="text-red-600 font-bold">{format(parseISO(invoice.due_date), 'M.d.yyyy')}</span>
              </div>
            </div>
          )}

          {/* Inline Edit Controls for Vendor */}
          {canEdit && (
            <div className="mt-4 pt-4 border-t border-slate-200 flex justify-end gap-2">
              {isEditingDetails ? (
                <>
                  <Button variant="outline" size="sm" onClick={handleCancelEdit}>
                    <X className="w-4 h-4 mr-1" />
                    Cancel
                  </Button>
                  <Button size="sm" className="bg-green-600 hover:bg-green-700" onClick={handleSaveDetails}>
                    <Save className="w-4 h-4 mr-1" />
                    Save Changes
                  </Button>
                </>
              ) : (
                <Button variant="outline" size="sm" onClick={() => setIsEditingDetails(true)}>
                  <Pencil className="w-4 h-4 mr-1" />
                  Edit Details
                </Button>
              )}
            </div>
          )}
        </div>



        {/* Dispute Alert for Vendors */}
        {invoice.status === "Disputed" && (isVendor || isAdmin) && (
          <div className="bg-red-50 border-2 border-red-200 rounded-xl p-6 mb-6">
            <div className="flex items-start gap-4">
              <div className="w-10 h-10 bg-red-500 rounded-full flex items-center justify-center flex-shrink-0">
                <Flag className="w-5 h-5 text-white" />
              </div>
              <div className="flex-1">
                <h3 className="font-bold text-red-800 text-lg mb-2">Invoice Disputed by Client</h3>
                <div className="grid grid-cols-2 gap-4 mb-4">
                  <div>
                    <p className="text-xs text-red-600 font-semibold">Reason</p>
                    <p className="text-red-900 font-medium">{invoice.dispute_reason || "Not specified"}</p>
                  </div>
                  <div>
                    <p className="text-xs text-red-600 font-semibold">Disputed By</p>
                    <p className="text-red-900">{invoice.disputed_by || "Client"}</p>
                  </div>
                </div>
                {invoice.dispute_details && (
                  <div className="mb-4">
                    <p className="text-xs text-red-600 font-semibold">Details</p>
                    <p className="text-red-900 bg-white p-3 rounded-lg border border-red-200 mt-1">{invoice.dispute_details}</p>
                  </div>
                )}
                {invoice.disputed_items && invoice.disputed_items.length > 0 && (
                  <div>
                    <p className="text-xs text-red-600 font-semibold mb-2">Disputed Line Items ({invoice.disputed_items.length})</p>
                    <div className="bg-white rounded-lg border border-red-200 overflow-hidden">
                      <table className="w-full text-sm">
                        <thead className="bg-red-100">
                          <tr>
                            <th className="p-2 text-left text-red-800">#</th>
                            <th className="p-2 text-left text-red-800">Staff</th>
                            <th className="p-2 text-left text-red-800">Position</th>
                            <th className="p-2 text-right text-red-800">Hours</th>
                            <th className="p-2 text-right text-red-800">Amount</th>
                          </tr>
                        </thead>
                        <tbody>
                          {invoice.disputed_items.map((item, idx) => {
                            const role = displayRoles[item.role_index];
                            const entry = role?.staff_entries?.[item.staff_index];
                            if (!entry) return null;
                            return (
                              <tr key={idx} className="border-t border-red-100">
                                <td className="p-2">{idx + 1}</td>
                                <td className="p-2 font-medium">{entry.staff_name || entry.name || "Staff"}</td>
                                <td className="p-2">{entry.position}</td>
                                <td className="p-2 text-right">{entry.worked_hours?.toFixed(2)}</td>
                                <td className="p-2 text-right font-semibold">${entry.total?.toFixed(2)}</td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                  </div>
                )}
                <div className="mt-4 flex gap-2">
                  <Button size="sm" className="bg-blue-600 hover:bg-blue-700" onClick={handleEditInvoice}>
                    <Edit className="w-4 h-4 mr-1" />
                    Edit & Fix Invoice
                  </Button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* From and To */}
        <div className="grid grid-cols-2 gap-6 mb-8">
          <div className="bg-blue-50 rounded-xl p-6 border-2 border-blue-200">
            <div className="flex items-center gap-2 mb-4">
              <div className="w-8 h-8 bg-[#0A39DF] rounded-full flex items-center justify-center">
                <span className="text-white font-bold text-sm">F</span>
              </div>
              <h3 className="font-bold text-lg text-slate-900">From:</h3>
            </div>
            {isEditingDetails ? (
              <div className="space-y-2">
                <div>
                  <Label className="text-xs text-slate-500">Company Name</Label>
                  <Input
                    value={editedDetails.from_company.name}
                    onChange={(e) => setEditedDetails({ 
                      ...editedDetails, 
                      from_company: { ...editedDetails.from_company, name: e.target.value } 
                    })}
                    className="h-8 mt-1"
                  />
                </div>
                <div>
                  <Label className="text-xs text-slate-500">Address</Label>
                  <Input
                    value={editedDetails.from_company.address}
                    onChange={(e) => setEditedDetails({ 
                      ...editedDetails, 
                      from_company: { ...editedDetails.from_company, address: e.target.value } 
                    })}
                    className="h-8 mt-1"
                  />
                </div>
                <div>
                  <Label className="text-xs text-slate-500">Email</Label>
                  <Input
                    value={editedDetails.from_company.email}
                    onChange={(e) => setEditedDetails({ 
                      ...editedDetails, 
                      from_company: { ...editedDetails.from_company, email: e.target.value } 
                    })}
                    className="h-8 mt-1"
                  />
                </div>
                <div>
                  <Label className="text-xs text-slate-500">Phone</Label>
                  <Input
                    value={editedDetails.from_company.phone}
                    onChange={(e) => setEditedDetails({ 
                      ...editedDetails, 
                      from_company: { ...editedDetails.from_company, phone: e.target.value } 
                    })}
                    className="h-8 mt-1"
                  />
                </div>
              </div>
            ) : (
              <div className="space-y-2">
                <p className="font-bold text-lg text-slate-900">{invoice.from_company?.name || invoice.vendor_name || "Vendor Name"}</p>
                {(invoice.from_company?.address || invoice.vendor_address) && (
                  <div className="text-sm text-slate-700">
                    <p className="font-semibold text-slate-500 text-xs mb-1">Address</p>
                    <p>{invoice.from_company?.address || invoice.vendor_address}</p>
                  </div>
                )}
                {(invoice.from_company?.email || invoice.vendor_email) && (
                  <div className="text-sm text-slate-700">
                    <p className="font-semibold text-slate-500 text-xs mb-1">Email</p>
                    <p>{invoice.from_company?.email || invoice.vendor_email}</p>
                  </div>
                )}
                {(invoice.from_company?.phone || invoice.vendor_phone) && (
                  <div className="text-sm text-slate-700">
                    <p className="font-semibold text-slate-500 text-xs mb-1">Phone</p>
                    <p>{invoice.from_company?.phone || invoice.vendor_phone}</p>
                  </div>
                )}
              </div>
            )}
          </div>

          <div className="bg-green-50 rounded-xl p-6 border-2 border-green-200">
            <div className="flex items-center gap-2 mb-4">
              <div className="w-8 h-8 bg-green-600 rounded-full flex items-center justify-center">
                <span className="text-white font-bold text-sm">T</span>
              </div>
              <h3 className="font-bold text-lg text-slate-900">To:</h3>
            </div>
            {isEditingDetails ? (
              <div className="space-y-2">
                <div>
                  <Label className="text-xs text-slate-500">Company Name</Label>
                  <Input
                    value={editedDetails.to_company.name}
                    onChange={(e) => setEditedDetails({ 
                      ...editedDetails, 
                      to_company: { ...editedDetails.to_company, name: e.target.value } 
                    })}
                    className="h-8 mt-1"
                  />
                </div>
                <div>
                  <Label className="text-xs text-slate-500">Address</Label>
                  <Input
                    value={editedDetails.to_company.address}
                    onChange={(e) => setEditedDetails({ 
                      ...editedDetails, 
                      to_company: { ...editedDetails.to_company, address: e.target.value } 
                    })}
                    className="h-8 mt-1"
                  />
                </div>
                <div>
                  <Label className="text-xs text-slate-500">Email</Label>
                  <Input
                    value={editedDetails.to_company.email}
                    onChange={(e) => setEditedDetails({ 
                      ...editedDetails, 
                      to_company: { ...editedDetails.to_company, email: e.target.value } 
                    })}
                    className="h-8 mt-1"
                  />
                </div>
                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <Label className="text-xs text-slate-500">Manager</Label>
                    <Input
                      value={editedDetails.to_company.manager}
                      onChange={(e) => setEditedDetails({ 
                        ...editedDetails, 
                        to_company: { ...editedDetails.to_company, manager: e.target.value } 
                      })}
                      className="h-8 mt-1"
                    />
                  </div>
                  <div>
                    <Label className="text-xs text-slate-500">Phone</Label>
                    <Input
                      value={editedDetails.to_company.phone}
                      onChange={(e) => setEditedDetails({ 
                        ...editedDetails, 
                        to_company: { ...editedDetails.to_company, phone: e.target.value } 
                      })}
                      className="h-8 mt-1"
                    />
                  </div>
                </div>
                <div>
                  <Label className="text-xs text-slate-500">Vendor #</Label>
                  <Input
                    value={editedDetails.to_company.vendor_id}
                    onChange={(e) => setEditedDetails({ 
                      ...editedDetails, 
                      to_company: { ...editedDetails.to_company, vendor_id: e.target.value } 
                    })}
                    className="h-8 mt-1"
                  />
                </div>
              </div>
            ) : (
              <div className="space-y-1 text-sm">
                <p className="font-bold text-slate-900">{invoice.to_company?.name || invoice.business_name}</p>
                <p className="text-slate-600">{invoice.to_company?.address}</p>
                <p className="text-slate-600">{invoice.to_company?.email}</p>
                <div className="grid grid-cols-2 gap-4 mt-3 pt-3 border-t border-green-200">
                  <div>
                    <p className="text-xs text-slate-500">Main Kitchen</p>
                    <p className="font-semibold text-slate-900">{invoice.to_company?.manager || invoice.manager_name}</p>
                  </div>
                  <div>
                    <p className="text-xs text-slate-500">Manager Name</p>
                    <p className="font-semibold text-slate-900">{invoice.to_company?.phone}</p>
                  </div>
                </div>
                <p className="text-slate-600">{invoice.to_company?.vendor_id || "Vendor #"}</p>
              </div>
            )}
          </div>
        </div>

        {/* Staff Charges Table */}
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden mb-6">
          {canEdit && (
            <div className="p-4 border-b border-slate-200 flex justify-between items-center bg-slate-50">
              <h3 className="font-semibold text-slate-900">Staff Entries</h3>
              <Button size="sm" onClick={handleAddEntry} className="bg-[#0A39DF] hover:bg-[#0831b8]">
                <Plus className="w-4 h-4 mr-1" />
                Add Position
              </Button>
            </div>
          )}
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-slate-50 border-b border-slate-200">
                <tr>
                  <th className="px-3 py-3 text-left text-xs font-semibold text-slate-600">#</th>
                  <th className="px-3 py-3 text-left text-xs font-semibold text-slate-600">Date</th>
                  <th className="px-3 py-3 text-left text-xs font-semibold text-slate-600">Position</th>
                  <th className="px-3 py-3 text-right text-xs font-semibold text-slate-600">Worked Hours</th>
                  <th className="px-3 py-3 text-right text-xs font-semibold text-slate-600">Reg Hours</th>
                  <th className="px-3 py-3 text-right text-xs font-semibold text-slate-600">OT Hours</th>
                  <th className="px-3 py-3 text-right text-xs font-semibold text-slate-600">DT Hours</th>
                  <th className="px-3 py-3 text-right text-xs font-semibold text-slate-600">Reg Value</th>
                  <th className="px-3 py-3 text-right text-xs font-semibold text-slate-600">OT Value</th>
                  <th className="px-3 py-3 text-right text-xs font-semibold text-slate-600">DT Value</th>
                  <th className="px-3 py-3 text-right text-xs font-semibold text-slate-600">Total</th>
                  <th className="px-3 py-3 text-center text-xs font-semibold text-slate-600">Actions</th>
                </tr>
              </thead>
              <tbody>
                {displayRoles?.map((roleGroup, roleIdx) => {
                  const groupedPositions = getGroupedByPosition(roleGroup.staff_entries || []);
                  let rowNumber = 0;

                  return (
                    <React.Fragment key={roleIdx}>
                      {groupedPositions.map((posGroup, posIdx) => {
                        const isExpanded = expandedPositions[`${roleIdx}-${posGroup.position}`];
                        const hasMultiple = posGroup.entries.length > 1;
                        rowNumber++;
                        const currentRowNum = rowNumber;

                        return (
                          <React.Fragment key={`${roleIdx}-${posIdx}`}>
                            {/* Position Summary Row */}
                            <tr className="border-b border-slate-100 bg-indigo-50/50">
                              <td className="px-3 py-3 text-sm text-slate-900">{currentRowNum}</td>
                              <td className="px-3 py-3 text-sm text-slate-600">
                                {hasMultiple ? '—' : (() => {
                                  const dateStr = posGroup.entries[0]?.date;
                                  if (!dateStr) return '—';
                                  try { return format(parseISO(dateStr), 'MM.dd.yyyy'); } catch { return dateStr; }
                                })()}
                              </td>
                              <td className="px-3 py-3 text-sm text-slate-900">{posGroup.position}</td>
                              <td className="px-3 py-3 text-sm text-right text-slate-700">{posGroup.totalWorkedHours.toFixed(2)}</td>
                              <td className="px-3 py-3 text-sm text-right text-slate-700">{posGroup.totalRegularHours.toFixed(2)}</td>
                              <td className="px-3 py-3 text-sm text-right text-slate-700">{posGroup.totalOtHours.toFixed(2)}</td>
                              <td className="px-3 py-3 text-sm text-right text-slate-700">{posGroup.totalDtHours.toFixed(2)}</td>
                              <td className="px-3 py-3 text-sm text-right text-slate-700">${posGroup.totalRegularValue.toFixed(2)}</td>
                              <td className="px-3 py-3 text-sm text-right text-slate-700">${posGroup.totalOtValue.toFixed(2)}</td>
                              <td className="px-3 py-3 text-sm text-right text-slate-700">${posGroup.totalDtValue.toFixed(2)}</td>
                              <td className="px-3 py-3 text-sm text-right font-semibold text-slate-900">${posGroup.total.toFixed(2)}</td>
                              <td className="px-3 py-3 text-center">
                                <div className="flex items-center justify-center gap-1">
                                  <Button 
                                    size="sm" 
                                    variant="ghost" 
                                    className="h-7 px-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded flex items-center gap-1" 
                                    title={isExpanded ? 'Collapse' : 'View Details'}
                                    onClick={() => togglePositionExpand(roleIdx, posGroup.position)}
                                  >
                                    <ChevronDown className={`w-4 h-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
                                  </Button>
                                  <Button 
                                    size="sm" 
                                    variant="ghost" 
                                    className="h-7 w-7 p-0 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded" 
                                    title="Edit" 
                                    onClick={(e) => { e.stopPropagation(); handleEditEntry(roleIdx, posGroup.entries[0].originalIndex, posGroup.entries[0]); }}
                                  >
                                    <Pencil className="w-4 h-4" />
                                  </Button>
                                  <Button 
                                    size="sm" 
                                    variant="ghost" 
                                    className={`h-7 w-7 p-0 rounded ${invoice.disputed_items?.some(item => item.role_index === roleIdx && item.staff_index === posGroup.entries[0].originalIndex) ? 'text-amber-600 bg-amber-50' : 'text-slate-400 hover:text-amber-600 hover:bg-amber-50'}`}
                                    title={invoice.disputed_items?.some(item => item.role_index === roleIdx && item.staff_index === posGroup.entries[0].originalIndex) ? 'Unflag' : 'Flag'}
                                    onClick={() => handleFlagEntry(roleIdx, posGroup.entries[0].originalIndex, posGroup.entries[0])}
                                  >
                                    <Flag className="w-4 h-4" />
                                  </Button>
                                  <Button 
                                    size="sm" 
                                    variant="ghost" 
                                    className="h-7 w-7 p-0 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded" 
                                    title="Remove" 
                                    onClick={() => handleRemoveEntry(roleIdx, posGroup.entries[0].originalIndex)}
                                  >
                                    <Trash2 className="w-4 h-4" />
                                  </Button>
                                </div>
                              </td>
                            </tr>

                            {/* Expanded Individual Entries - Sub-table with detailed columns */}
                            {isExpanded && (
                              <tr>
                                <td colSpan="12" className="p-0 bg-slate-50">
                                  <table className="w-full text-sm">
                                    <thead className="bg-slate-100 border-y border-slate-200">
                                      <tr>
                                        <th className="px-3 py-2 text-left text-xs font-semibold text-slate-600">#</th>
                                        <th className="px-3 py-2 text-left text-xs font-semibold text-slate-600">Name</th>
                                        <th className="px-3 py-2 text-left text-xs font-semibold text-slate-600">Clockin</th>
                                        <th className="px-3 py-2 text-left text-xs font-semibold text-slate-600">Lunch</th>
                                        <th className="px-3 py-2 text-left text-xs font-semibold text-slate-600">Clockout</th>
                                        <th className="px-3 py-2 text-right text-xs font-semibold text-slate-600">Worked Hours</th>
                                        <th className="px-3 py-2 text-right text-xs font-semibold text-slate-600">Reg Hours</th>
                                        <th className="px-3 py-2 text-right text-xs font-semibold text-slate-600">OT Hours</th>
                                        <th className="px-3 py-2 text-right text-xs font-semibold text-slate-600">DT Hours</th>
                                        <th className="px-3 py-2 text-right text-xs font-semibold text-slate-600">Rate</th>
                                        <th className="px-3 py-2 text-right text-xs font-semibold text-slate-600">Reg Value</th>
                                        <th className="px-3 py-2 text-right text-xs font-semibold text-slate-600">OT Value</th>
                                        <th className="px-3 py-2 text-right text-xs font-semibold text-slate-600">DT Value</th>
                                        <th className="px-3 py-2 text-right text-xs font-semibold text-slate-600">Total</th>
                                        <th className="px-3 py-2 text-center text-xs font-semibold text-slate-600">Actions</th>
                                      </tr>
                                    </thead>
                                    <tbody>
                                      {posGroup.entries.map((entry, entryIdx) => {
                                        const isFlagged = invoice.disputed_items?.some(item => item.role_index === roleIdx && item.staff_index === entry.originalIndex);
                                        return (
                                          <tr key={`detail-${roleIdx}-${entry.originalIndex}`} className={`border-b border-slate-100 ${isFlagged ? 'bg-red-50' : 'bg-white'}`}>
                                            <td className="px-3 py-2 text-sm text-slate-500">{entryIdx + 1}</td>
                                            <td className="px-3 py-2 text-sm text-slate-900">
                                              {editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? (
                                                <div className="flex gap-1">
                                                  <Input 
                                                    value={editedEntry?.staff_name || editedEntry?.name || ''} 
                                                    onChange={(e) => setEditedEntry({...editedEntry, staff_name: e.target.value, name: e.target.value})}
                                                    className="h-7 w-20 text-xs"
                                                    placeholder="Name"
                                                  />
                                                  <Select 
                                                    value={editedEntry?.position || ''} 
                                                    onValueChange={(val) => setEditedEntry({...editedEntry, position: val})}
                                                  >
                                                    <SelectTrigger className="h-7 w-24 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>
                                                </div>
                                              ) : (entry.staff_name || entry.name || '—')}
                                            </td>
                                            <td className="px-3 py-2 text-sm text-slate-600">
                                              {editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? (
                                                <Input 
                                                  value={editedEntry?.check_in || ''} 
                                                  onChange={(e) => {
                                                    const updated = {...editedEntry, check_in: e.target.value};
                                                    setEditedEntry(recalculateEntry(updated));
                                                  }}
                                                  placeholder="09:00 AM"
                                                  className="h-7 w-20 text-xs"
                                                />
                                              ) : (entry.check_in || '—')}
                                            </td>
                                            <td className="px-3 py-2 text-sm text-slate-600">
                                              {editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? (
                                                <Select 
                                                  value={String(editedEntry?.lunch || '0')} 
                                                  onValueChange={(val) => {
                                                    const updated = {...editedEntry, lunch: val === 'NB' ? 'NB' : parseInt(val)};
                                                    setEditedEntry(recalculateEntry(updated));
                                                  }}
                                                >
                                                  <SelectTrigger className="h-7 w-16 text-xs"><SelectValue /></SelectTrigger>
                                                  <SelectContent>
                                                    <SelectItem value="NB">NB</SelectItem>
                                                    <SelectItem value="0">0</SelectItem>
                                                    <SelectItem value="15">15</SelectItem>
                                                    <SelectItem value="30">30</SelectItem>
                                                    <SelectItem value="45">45</SelectItem>
                                                    <SelectItem value="60">60</SelectItem>
                                                  </SelectContent>
                                                </Select>
                                              ) : (entry.lunch || '0')}
                                            </td>
                                            <td className="px-3 py-2 text-sm text-slate-600">
                                              {editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? (
                                                <Input 
                                                  value={editedEntry?.check_out || ''} 
                                                  onChange={(e) => {
                                                    const updated = {...editedEntry, check_out: e.target.value};
                                                    setEditedEntry(recalculateEntry(updated));
                                                  }}
                                                  placeholder="05:00 PM"
                                                  className="h-7 w-20 text-xs"
                                                />
                                              ) : (entry.check_out || '—')}
                                            </td>
                                            <td className="px-3 py-2 text-sm text-right text-slate-700">{editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? editedEntry?.worked_hours?.toFixed(2) : entry.worked_hours?.toFixed(2) || '0.00'}</td>
                                            <td className="px-3 py-2 text-sm text-right text-slate-700">{editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? editedEntry?.regular_hours?.toFixed(2) : entry.regular_hours?.toFixed(2) || '0.00'}</td>
                                            <td className="px-3 py-2 text-sm text-right text-slate-700">{editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? editedEntry?.ot_hours?.toFixed(2) : entry.ot_hours?.toFixed(2) || '0.00'}</td>
                                            <td className="px-3 py-2 text-sm text-right text-slate-700">{editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? editedEntry?.dt_hours?.toFixed(2) : entry.dt_hours?.toFixed(2) || '0.00'}</td>
                                            <td className="px-3 py-2 text-sm text-right text-slate-700">
                                              {editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? (
                                                <Input 
                                                  type="number"
                                                  step="0.01"
                                                  value={editedEntry?.rate || 0} 
                                                  onChange={(e) => {
                                                    const updated = {...editedEntry, rate: parseFloat(e.target.value) || 0};
                                                    setEditedEntry(recalculateEntry(updated));
                                                  }}
                                                  className="h-7 w-16 text-xs text-right"
                                                />
                                              ) : `$${entry.rate?.toFixed(2) || '0.00'}`}
                                            </td>
                                            <td className="px-3 py-2 text-sm text-right text-slate-700">${editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? editedEntry?.regular_value?.toFixed(2) : entry.regular_value?.toFixed(2) || '0.00'}</td>
                                            <td className="px-3 py-2 text-sm text-right text-slate-700">${editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? editedEntry?.ot_value?.toFixed(2) : entry.ot_value?.toFixed(2) || '0.00'}</td>
                                            <td className="px-3 py-2 text-sm text-right text-slate-700">${editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? editedEntry?.dt_value?.toFixed(2) : entry.dt_value?.toFixed(2) || '0.00'}</td>
                                            <td className="px-3 py-2 text-sm text-right font-semibold text-slate-900">${editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? editedEntry?.total?.toFixed(2) : entry.total?.toFixed(2) || '0.00'}</td>
                                            <td className="px-3 py-2 text-center">
                                                <div className="flex items-center justify-center gap-1">
                                                  {editingEntryIndex?.roleIdx === roleIdx && editingEntryIndex?.entryIdx === entry.originalIndex ? (
                                                    <>
                                                      <Button 
                                                        size="sm" 
                                                        variant="ghost" 
                                                        className="h-7 w-7 p-0 text-green-600 hover:text-green-700 hover:bg-green-50 rounded" 
                                                        title="Save" 
                                                        onClick={handleSaveEntry}
                                                      >
                                                        <Save className="w-4 h-4" />
                                                      </Button>
                                                      <Button 
                                                        size="sm" 
                                                        variant="ghost" 
                                                        className="h-7 w-7 p-0 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded" 
                                                        title="Cancel" 
                                                        onClick={() => { setEditingEntryIndex(null); setEditedEntry(null); }}
                                                      >
                                                        <X className="w-4 h-4" />
                                                      </Button>
                                                    </>
                                                  ) : (
                                                    <>
                                                      <Button 
                                                        size="sm" 
                                                        variant="ghost" 
                                                        className="h-7 w-7 p-0 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded" 
                                                        title="Edit" 
                                                        onClick={() => handleEditEntry(roleIdx, entry.originalIndex, entry)}
                                                      >
                                                        <Pencil className="w-4 h-4" />
                                                      </Button>
                                                      <Button 
                                                        size="sm" 
                                                        variant="ghost" 
                                                        className={`h-7 w-7 p-0 rounded ${invoice.disputed_items?.some(item => item.role_index === roleIdx && item.staff_index === entry.originalIndex) ? 'text-amber-600 bg-amber-50' : 'text-slate-400 hover:text-amber-600 hover:bg-amber-50'}`}
                                                        title={invoice.disputed_items?.some(item => item.role_index === roleIdx && item.staff_index === entry.originalIndex) ? 'Unflag' : 'Flag'}
                                                        onClick={() => handleFlagEntry(roleIdx, entry.originalIndex, entry)}
                                                      >
                                                        <Flag className="w-4 h-4" />
                                                      </Button>
                                                      <Button 
                                                        size="sm" 
                                                        variant="ghost" 
                                                        className="h-7 w-7 p-0 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded" 
                                                        title="Remove" 
                                                        onClick={() => handleRemoveEntry(roleIdx, entry.originalIndex)}
                                                      >
                                                        <Trash2 className="w-4 h-4" />
                                                      </Button>
                                                    </>
                                                  )}
                                                </div>
                                              </td>
                                          </tr>
                                        );
                                      })}
                                      {/* Sub-table Total Row */}
                                      <tr className="border-t-2 border-slate-200 bg-slate-50">
                                        <td className="px-3 py-2"></td>
                                        <td className="px-3 py-2"></td>
                                        <td className="px-3 py-2"></td>
                                        <td className="px-3 py-2"></td>
                                        <td className="px-3 py-2 text-sm font-semibold text-slate-900">Total</td>
                                        <td className="px-3 py-2 text-sm text-right font-semibold text-slate-900">{posGroup.totalWorkedHours.toFixed(2)}</td>
                                        <td className="px-3 py-2 text-sm text-right font-semibold text-slate-900">{posGroup.totalRegularHours.toFixed(2)}</td>
                                        <td className="px-3 py-2 text-sm text-right font-semibold text-slate-900">{posGroup.totalOtHours.toFixed(2)}</td>
                                        <td className="px-3 py-2 text-sm text-right font-semibold text-slate-900">{posGroup.totalDtHours.toFixed(2)}</td>
                                        <td className="px-3 py-2"></td>
                                        <td className="px-3 py-2 text-sm text-right font-semibold text-slate-900">${posGroup.totalRegularValue.toFixed(2)}</td>
                                        <td className="px-3 py-2 text-sm text-right font-semibold text-slate-900">${posGroup.totalOtValue.toFixed(2)}</td>
                                        <td className="px-3 py-2 text-sm text-right font-semibold text-slate-900">${posGroup.totalDtValue.toFixed(2)}</td>
                                        <td className="px-3 py-2 text-sm text-right font-bold text-slate-900">${posGroup.total.toFixed(2)}</td>
                                        <td className="px-3 py-2"></td>
                                      </tr>
                                    </tbody>
                                  </table>
                                </td>
                              </tr>
                            )}
                          </React.Fragment>
                        );
                      })}
                      {/* Total Row */}
                      <tr className="border-t-2 border-slate-200 bg-white">
                        <td className="px-3 py-3"></td>
                        <td className="px-3 py-3"></td>
                        <td className="px-3 py-3 text-sm font-semibold text-slate-900">Total</td>
                        <td className="px-3 py-3 text-sm text-right font-semibold text-slate-900">
                          {groupedPositions.reduce((sum, g) => sum + g.totalWorkedHours, 0).toFixed(2)}
                        </td>
                        <td className="px-3 py-3 text-sm text-right font-semibold text-slate-900">
                          {groupedPositions.reduce((sum, g) => sum + g.totalRegularHours, 0).toFixed(2)}
                        </td>
                        <td className="px-3 py-3 text-sm text-right font-semibold text-slate-900">
                          {groupedPositions.reduce((sum, g) => sum + g.totalOtHours, 0).toFixed(2)}
                        </td>
                        <td className="px-3 py-3 text-sm text-right font-semibold text-slate-900">
                          {groupedPositions.reduce((sum, g) => sum + g.totalDtHours, 0).toFixed(2)}
                        </td>
                        <td className="px-3 py-3 text-sm text-right font-semibold text-slate-900">
                          ${groupedPositions.reduce((sum, g) => sum + g.totalRegularValue, 0).toFixed(2)}
                        </td>
                        <td className="px-3 py-3 text-sm text-right font-semibold text-slate-900">
                          ${groupedPositions.reduce((sum, g) => sum + g.totalOtValue, 0).toFixed(2)}
                        </td>
                        <td className="px-3 py-3 text-sm text-right font-semibold text-slate-900">
                          ${groupedPositions.reduce((sum, g) => sum + g.totalDtValue, 0).toFixed(2)}
                        </td>
                        <td className="px-3 py-3 text-sm text-right font-bold text-slate-900">
                          ${roleGroup.role_subtotal?.toFixed(2)}
                        </td>
                        <td className="px-3 py-3"></td>
                      </tr>
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        {/* Other Charges and Total Section - Side by Side */}
        <div className="grid grid-cols-2 gap-6 mb-6">
          {/* Other Charges */}
          <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
            <div className="px-4 py-3 border-b border-slate-200">
              <h3 className="font-semibold text-slate-900">Other charges</h3>
            </div>
            <table className="w-full text-sm">
              <thead className="bg-slate-50 border-b border-slate-200">
                <tr>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">#</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Charge</th>
                  <th className="px-4 py-2 text-right text-xs font-semibold text-slate-600">QTY</th>
                  <th className="px-4 py-2 text-right text-xs font-semibold text-slate-600">Rate</th>
                  <th className="px-4 py-2 text-right text-xs font-semibold text-slate-600">Amount</th>
                </tr>
              </thead>
              <tbody>
                {invoice.other_charges > 0 ? (
                  <tr className="border-b border-slate-100">
                    <td className="px-4 py-3 text-sm text-slate-600">1</td>
                    <td className="px-4 py-3 text-sm text-slate-900">Additional Charges</td>
                    <td className="px-4 py-3 text-sm text-right text-slate-600">1</td>
                    <td className="px-4 py-3 text-sm text-right text-slate-600">${invoice.other_charges?.toFixed(2)}</td>
                    <td className="px-4 py-3 text-sm text-right font-semibold text-slate-900">${invoice.other_charges?.toFixed(2)}</td>
                  </tr>
                ) : (
                  <tr>
                    <td colSpan="5" className="px-4 py-6 text-center text-sm text-slate-400">No other charges</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {/* Total */}
          <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
            <div className="px-4 py-3 border-b border-slate-200">
              <h3 className="font-semibold text-slate-900">Total</h3>
            </div>
            <div className="p-4 space-y-3">
              <div className="flex justify-between text-sm">
                <span className="text-slate-600">Sub total:</span>
                <span className="font-semibold text-slate-900">${displaySubtotal?.toFixed(2)}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-slate-600">Other charges:</span>
                <span className="font-semibold text-slate-900">${(invoice.other_charges || 0)?.toFixed(2)}</span>
              </div>
              <div className="border-t border-slate-200 pt-3 flex justify-between">
                <span className="font-bold text-slate-900">Grand total:</span>
                <span className="font-bold text-lg text-slate-900">${displayAmount?.toFixed(2)}</span>
              </div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="mt-8 flex items-center justify-between text-sm text-slate-500">
          <div className="flex items-center gap-2">
            <span className="text-slate-400">Invoice powered by</span>
            <img 
              src="https://qtrypzzcjebvfcihiynt.supabase.co/storage/v1/object/public/base44-prod/public/68fc6cf01386035c266e7a5d/3ba390829_KROWlogo.png" 
              alt="KROW" 
              className="h-6"
            />
          </div>
          <span>Page 1</span>
        </div>
      </div>

      {/* Dispute Dialog */}
      <Dialog open={showDisputeDialog} onOpenChange={setShowDisputeDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Flag className="w-5 h-5 text-red-500" />
              Dispute Invoice - Select Items
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            {/* Select items to dispute */}
            <div>
              <Label className="text-sm font-semibold mb-2 block">Select line items to dispute:</Label>
              <div className="border rounded-lg overflow-hidden">
                <table className="w-full text-sm">
                  <thead className="bg-slate-50">
                    <tr>
                      <th className="p-2 text-left w-10">
                        <input 
                          type="checkbox" 
                          className="rounded"
                          onChange={(e) => {
                            if (e.target.checked) {
                              const allItems = [];
                              displayRoles.forEach((role, rIdx) => {
                                role.staff_entries?.forEach((_, sIdx) => {
                                  allItems.push({ role_index: rIdx, staff_index: sIdx });
                                });
                              });
                              setSelectedItems(allItems);
                            } else {
                              setSelectedItems([]);
                            }
                          }}
                        />
                      </th>
                      <th className="p-2 text-left">Staff</th>
                      <th className="p-2 text-left">Position</th>
                      <th className="p-2 text-right">Hours</th>
                      <th className="p-2 text-right">Total</th>
                    </tr>
                  </thead>
                  <tbody>
                    {displayRoles.map((role, rIdx) => (
                      role.staff_entries?.map((entry, sIdx) => {
                        const isSelected = selectedItems.some(
                          item => item.role_index === rIdx && item.staff_index === sIdx
                        );
                        return (
                          <tr 
                            key={`${rIdx}-${sIdx}`} 
                            className={`border-t cursor-pointer transition-colors ${isSelected ? 'bg-red-50' : 'hover:bg-slate-50'}`}
                            onClick={() => toggleItemSelection(rIdx, sIdx)}
                          >
                            <td className="p-2">
                              <input 
                                type="checkbox" 
                                checked={isSelected}
                                onChange={() => toggleItemSelection(rIdx, sIdx)}
                                className="rounded"
                              />
                            </td>
                            <td className="p-2 font-medium">{entry.staff_name || entry.name || "Staff Member"}</td>
                            <td className="p-2 text-slate-600">{entry.position}</td>
                            <td className="p-2 text-right">{entry.worked_hours?.toFixed(2)}</td>
                            <td className="p-2 text-right font-semibold">${entry.total?.toFixed(2)}</td>
                          </tr>
                        );
                      })
                    ))}
                  </tbody>
                </table>
              </div>
              {selectedItems.length > 0 && (
                <p className="text-sm text-red-600 mt-2 font-medium">
                  {selectedItems.length} item(s) selected for dispute
                </p>
              )}
            </div>

            <div>
              <Label>Reason for Dispute</Label>
              <Select value={disputeReason} onValueChange={setDisputeReason}>
                <SelectTrigger>
                  <SelectValue placeholder="Select reason" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="Incorrect Hours">Incorrect Hours</SelectItem>
                  <SelectItem value="Incorrect Rate">Incorrect Rate</SelectItem>
                  <SelectItem value="Unauthorized Staff">Unauthorized Staff</SelectItem>
                  <SelectItem value="Service Not Rendered">Service Not Rendered</SelectItem>
                  <SelectItem value="Calculation Error">Calculation Error</SelectItem>
                  <SelectItem value="Other">Other</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label>Details (explain what needs to be corrected)</Label>
              <Textarea
                value={disputeDetails}
                onChange={(e) => setDisputeDetails(e.target.value)}
                placeholder="E.g., 'Staff member worked 6 hours, not 8 hours as listed. Please adjust accordingly.'"
                rows={4}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDisputeDialog(false)}>
              Cancel
            </Button>
            <Button 
              onClick={handleDispute}
              disabled={!disputeReason || selectedItems.length === 0}
              className="bg-red-600 hover:bg-red-700"
            >
              Submit Dispute ({selectedItems.length} items)
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}