'use client';

import React, { useState, useEffect, useMemo, useRef } from 'react';
import MainLayout from '@/components/layout/MainLayout';
import * as XLSX from 'xlsx';
import { calculateShipDate, formatDateToYYYYMMDD } from '@/lib/dateUtils';
import MasterAwbReportModal from '@/components/reports/MasterAwbReportModal';

type BoxTypeItem = {
  id: string;
  code: string;
  name: string;
  length?: number | null;
  width?: number | null;
  height?: number | null;
  dimWeight?: number | null;
  realWeight?: number | null;
  farmId?: string | null;
  farmName?: string | null;
};

type Farm = {
  id: string;
  name: string;
  ruc?: string | null;
  farmCode?: string | null;
  country?: string | null;
  phone?: string | null;
  contactName?: string | null;
  emailOrders?: string | null;
};

type Product = {
  id: string;
  code: string;
  name: string;
  boxType?: string | null;
  stems?: number | null;
  declaredValue?: number | null;
};

type AirwayBill = {
  id: string;
  agency: string;
  deliverDate: string;
  shipDate: string;
  awb: string;
  master: string;
  status: string;
  notes?: string | null;
};

type SummaryLine = {
  id: string;
  orderId: string;
  po: string;
  orderNumber: string;
  item: string;
  prodDesc: string;
  orddate: string;
  shipdt: string;
  deliver: string;
  qty: number;
  farmAssigned: number;
  received: number;
  faltante: number;
  farmId?: string | null;
  farmName?: string;
  farmRuc?: string;
  awb?: string;
  agency?: string;
  boxNumber?: string;
  uniqueCode?: string;
  boxType?: string;
  farmPrice?: number;
  status: string;
  customerName?: string;
  masterName?: string;
  shippingName?: string;
  billingName?: string;
  farmDepartureDate?: string;
};

type SummaryGroup = {
  groupKey: string;
  item: string;
  prodDesc: string;
  shipdt: string;
  deliver: string;
  totalQty: number;
  totalFarmAssigned: number;
  totalReceived: number;
  totalFaltante: number;
  lines: SummaryLine[];
};

type FarmOrderLineItem = {
  itemCode: string;
  prodDesc: string;
  orderQty: number;
  farmQty: number;
  boxType: string;
  unitPrice: number;
  farmDepartureDate: string;
  shipDate: string;
  deliverDate: string;
};

type QcRejectionItem = {
  id: string;
  farmId?: string | null;
  farm?: { id?: string; name: string; ruc?: string } | null;
  boxNumber?: string | null;
  productCode?: string | null;
  productName?: string | null;
  reason: string;
  photoUrl?: string | null;
  price?: number | null;
  createdAt: string;
  creditApplied: boolean;
};

type CancelledLabelItem = {
  id: string;
  orderLineId?: string | null;
  boxNumber: string;
  uniqueCode: string;
  itemCode: string;
  productName: string;
  farmId?: string | null;
  farmName?: string | null;
  customerName?: string | null;
  po?: string | null;
  airwayBill?: string | null;
  agency?: string | null;
  boxType?: string | null;
  farmPrice?: number | null;
  farmDepartureDate?: string | null;
  orderDate?: string | null;
  cancelledAt: string;
  reason?: string | null;
};

type HistorialGroup = {
  groupKey: string;
  customerName: string;
  pos: string[];
  farmId: string;
  farmName: string;
  item: string;
  prodDesc: string;
  farmPrice: number;
  orddate: string;
  farmDepartureDate: string;
  shipdt: string;
  deliver: string;
  agency: string;
  awb: string;
  boxType: string;
  status: string;
  lines: SummaryLine[];
  lineIds: string[];
  qtyActual: number;
  cancelledCount: number;
  qtyOrdered: number;
  boxNumbers: string[];
  uniqueCodes: string[];
};

type EditModalItem = {
  id: string;
  lineIds: string[];
  orderedQty: number;
  newQty: number;
  productId: string;
  productCode: string;
  productName: string;
  farmId: string;
  farmName: string;
  farmPrice: number;
  farmDepartureDate: string;
  boxType: string;
  airwayBill: string;
  agency: string;
};

export default function PedidosFincasPage() {
  const [currentUser, setCurrentUser] = useState<any>(null);
  const [activeTab, setActiveTab] = useState<'PEDIDOS' | 'GUIAS' | 'HISTORIAL' | 'RECHAZOS' | 'CANCELADAS'>('PEDIDOS');
  
  // Data states
  const [groupedSummary, setGroupedSummary] = useState<SummaryGroup[]>([]);
  const [flatLines, setFlatLines] = useState<SummaryLine[]>([]);
  const [grandTotals, setGrandTotals] = useState({ qty: 0, farmAssigned: 0, received: 0, faltante: 0, totalLines: 0 });
  const [farms, setFarms] = useState<Farm[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [guias, setGuias] = useState<AirwayBill[]>([]);
  const [rejections, setRejections] = useState<QcRejectionItem[]>([]);
  const [cancelledLabels, setCancelledLabels] = useState<CancelledLabelItem[]>([]);
  const [masterCustomerOptions, setMasterCustomerOptions] = useState<string[]>([]);
  const [boxTypes, setBoxTypes] = useState<BoxTypeItem[]>([]);
  const [selectedAwbForReport, setSelectedAwbForReport] = useState<{ awb: string; agency?: string } | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [lastSyncTime, setLastSyncTime] = useState<string>('');

  // Filters for Summary Table (Tab 1)
  const [filters, setFilters] = useState({
    masterCustomer: '',
    shipToCustomer: '',
    po: '',
    order: '',
    item: '',
    prodDesc: '',
    salidaFinca: '',
    shipdateMode: 'single', // 'single' | 'range'
    shipdate: '',
    shipdateFrom: '',
    shipdateTo: '',
    deliverMode: 'single', // 'single' | 'range'
    deliver: '',
    deliverFrom: '',
    deliverTo: '',
    farm: '',
    awb: '',
    agency: ''
  });

  // Filters for Historial Table (Tab 3) - Draft input state
  const [historialFilters, setHistorialFilters] = useState({
    customer: '',
    farmId: '',
    item: '',
    prodDesc: '',
    price: '',
    departureDate: '',
    deliverDate: '',
    agency: '',
    awb: ''
  });
  // Applied filters that actually filter the Historial Table (Tab 3)
  const [appliedHistorialFilters, setAppliedHistorialFilters] = useState({
    customer: '',
    farmId: '',
    item: '',
    prodDesc: '',
    price: '',
    departureDate: '',
    deliverDate: '',
    agency: '',
    awb: ''
  });
  const [historialViewMode, setHistorialViewMode] = useState<'GROUPED' | 'INDIVIDUAL'>('GROUPED');
  const [historialSearchCancelled, setHistorialSearchCancelled] = useState('');

  // Historial Selection & Multi-Edit Modal States
  const [selectedHistorialIds, setSelectedHistorialIds] = useState<Set<string>>(new Set());
  const [multiEditModal, setMultiEditModal] = useState<{
    isOpen: boolean;
    title: string;
    items: EditModalItem[];
  } | null>(null);
  const [savingLineAction, setSavingLineAction] = useState(false);

  // "Place Order" Form State
  const [selectedFarmId, setSelectedFarmId] = useState('');
  const [selectedAgency, setSelectedAgency] = useState('FEDEX');
  const [selectedAwb, setSelectedAwb] = useState('');
  const [orderLinesForm, setOrderLinesForm] = useState<FarmOrderLineItem[]>([]);
  const [placingOrder, setPlacingOrder] = useState(false);
  const [orderSuccessModal, setOrderSuccessModal] = useState<{
    message: string;
    notice: string;
    lineIds: string[];
    details: any[];
  } | null>(null);

  // Guías Form State
  const [guiaModalOpen, setGuiaModalOpen] = useState(false);
  const [guiaEditingId, setGuiaEditingId] = useState<string | null>(null);
  const [guiaForm, setGuiaForm] = useState({
    agency: 'FEDEX',
    deliverDate: '',
    shipDate: '',
    awb: '',
    master: '',
    notes: ''
  });
  const [savingGuia, setSavingGuia] = useState(false);
  const [guiaError, setGuiaError] = useState('');
  const [guiaViewMode, setGuiaViewMode] = useState<'ACTIVE' | 'ARCHIVED' | 'ALL'>('ACTIVE');
  const [selectedGuiaIds, setSelectedGuiaIds] = useState<Set<string>>(new Set());

  // Expanded groups in Summary Table (all hidden by default until user clicks "Ver POs")
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());

  // Ref to always hold latest filters for background polling (avoids stale closures)
  const filtersRef = useRef(filters);
  useEffect(() => {
    filtersRef.current = filters;
  }, [filters]);

  // Ref to store fingerprint of last fetched summary data to detect actual changes
  const lastSummarySignatureRef = useRef<string>('');

  // Fetch summary & supporting data with silent change detection
  const fetchData = async (mode: 'initial' | 'manual' | 'background' | boolean = 'manual') => {
    const isBg = mode === 'background' || mode === false;
    const isInitial = mode === 'initial';
    const isManual = mode === 'manual' || mode === true;

    if (isInitial) setLoading(true);
    else if (isManual) setRefreshing(true);
    // Background polling is completely silent: NO loading spinner, NO button disabling/spinning!

    try {
      // Determine effective user
      const user = currentUser || (() => {
        try {
          const s = localStorage.getItem('usf_user') || localStorage.getItem('usf_farm_user');
          return s ? JSON.parse(s) : null;
        } catch { return null; }
      })();

      // ALWAYS read latest active filters from ref
      const curFilters = filtersRef.current;
      const queryParams = new URLSearchParams();
      if (user?.role === 'FARM' && user.farmId) {
        queryParams.set('farmId', user.farmId);
      }
      if (curFilters.masterCustomer.trim()) queryParams.set('masterCustomer', curFilters.masterCustomer.trim());
      if (curFilters.shipToCustomer.trim()) queryParams.set('shipToCustomer', curFilters.shipToCustomer.trim());
      if (curFilters.po.trim()) queryParams.set('po', curFilters.po.trim());
      if (curFilters.order.trim()) queryParams.set('order', curFilters.order.trim());
      if (curFilters.item.trim()) queryParams.set('item', curFilters.item.trim());
      if (curFilters.prodDesc.trim()) queryParams.set('prodDesc', curFilters.prodDesc.trim());
      if (curFilters.salidaFinca.trim()) queryParams.set('salidaFinca', curFilters.salidaFinca.trim());
      if (curFilters.farm.trim()) queryParams.set('farm', curFilters.farm.trim());
      if (curFilters.awb.trim()) queryParams.set('awb', curFilters.awb.trim());
      if (curFilters.agency.trim()) queryParams.set('agency', curFilters.agency.trim());

      if (curFilters.shipdateMode === 'single') {
        if (curFilters.shipdate) queryParams.set('shipdate', curFilters.shipdate);
      } else {
        if (curFilters.shipdateFrom) queryParams.set('shipdateFrom', curFilters.shipdateFrom);
        if (curFilters.shipdateTo) queryParams.set('shipdateTo', curFilters.shipdateTo);
      }

      if (curFilters.deliverMode === 'single') {
        if (curFilters.deliver) queryParams.set('deliver', curFilters.deliver);
      } else {
        if (curFilters.deliverFrom) queryParams.set('deliverFrom', curFilters.deliverFrom);
        if (curFilters.deliverTo) queryParams.set('deliverTo', curFilters.deliverTo);
      }

      const farmParam = user?.role === 'FARM' && user.farmId ? `?farmId=${user.farmId}` : '';

      // If background polling, only fetch summary and rejections to minimize overhead
      if (isBg) {
        const [summaryRes, rejectionsRes] = await Promise.all([
          fetch(`/api/pedidos/summary?${queryParams.toString()}`),
          fetch(`/api/pedidos/rejections${farmParam}`)
        ]);

        if (summaryRes.ok) {
          const data = await summaryRes.json();
          // Signature of data to detect additions, deletions, or edits
          const signature = JSON.stringify({
            grouped: data.grouped,
            flatCount: data.flatLines?.length,
            flatSample: data.flatLines ? [data.flatLines[0], data.flatLines[data.flatLines.length - 1]] : [],
            totals: data.grandTotals,
            cancelled: data.cancelledLabels
          });

          // ONLY update state if real change is detected
          if (signature !== lastSummarySignatureRef.current) {
            lastSummarySignatureRef.current = signature;
            setGroupedSummary(data.grouped || []);
            setFlatLines(data.flatLines || []);
            setGrandTotals(data.grandTotals || { qty: 0, farmAssigned: 0, received: 0, faltante: 0, totalLines: 0 });
            if (data.cancelledLabels) {
              setCancelledLabels(data.cancelledLabels);
            }
            setLastSyncTime(new Date().toLocaleTimeString());
          }
        }

        if (rejectionsRes.ok) {
          const rData = await rejectionsRes.json();
          setRejections(rData || []);
        }
        return;
      }

      // Initial or Manual refresh: fetch all including catalogs
      const [summaryRes, farmsRes, productsRes, guiasRes, rejectionsRes, customersRes, boxTypesRes] = await Promise.all([
        fetch(`/api/pedidos/summary?${queryParams.toString()}`),
        fetch('/api/farms'),
        fetch('/api/products'),
        fetch('/api/guias'),
        fetch(`/api/pedidos/rejections${farmParam}`),
        fetch('/api/customers'),
        fetch('/api/parametros/boxtype')
      ]);

      if (customersRes.ok) {
        const custs = await customersRes.json();
        if (Array.isArray(custs)) {
          const mastersOnly = custs
            .filter((c: any) => c.isMaster)
            .map((c: any) => c.businessName?.trim())
            .filter((n): n is string => Boolean(n))
            .sort((a, b) => a.localeCompare(b));
          setMasterCustomerOptions(mastersOnly);
        }
      }

      if (summaryRes.ok) {
        const data = await summaryRes.json();
        const signature = JSON.stringify({
          grouped: data.grouped,
          flatCount: data.flatLines?.length,
          flatSample: data.flatLines ? [data.flatLines[0], data.flatLines[data.flatLines.length - 1]] : [],
          totals: data.grandTotals,
          cancelled: data.cancelledLabels
        });
        lastSummarySignatureRef.current = signature;

        setGroupedSummary(data.grouped || []);
        setFlatLines(data.flatLines || []);
        setGrandTotals(data.grandTotals || { qty: 0, farmAssigned: 0, received: 0, faltante: 0, totalLines: 0 });
        if (data.cancelledLabels) {
          setCancelledLabels(data.cancelledLabels);
        }

        // Only collapse groups on INITIAL load, NEVER during ongoing work or refresh
        if (isInitial) {
          setExpandedGroups(new Set());
        }
      }
      if (farmsRes.ok) setFarms(await farmsRes.json());
      if (productsRes.ok) setProducts(await productsRes.json());
      if (guiasRes.ok) setGuias(await guiasRes.json());
      if (rejectionsRes.ok) setRejections(await rejectionsRes.json());
      if (boxTypesRes.ok) {
        const bData = await boxTypesRes.json();
        if (Array.isArray(bData)) setBoxTypes(bData);
      }

      fetch(`/api/pedidos/cancelled-labels${farmParam}`)
        .then(r => r.json())
        .then(d => { if (d.cancelledLabels) setCancelledLabels(d.cancelledLabels); })
        .catch(() => {});

      const now = new Date();
      setLastSyncTime(now.toLocaleTimeString());
    } catch (err) {
      console.error('Error loading pedidos data:', err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    // Check cached user
    const saved = localStorage.getItem('usf_user') || localStorage.getItem('usf_farm_user');
    if (saved) {
      try {
        const u = JSON.parse(saved);
        setCurrentUser(u);
        if (u.role === 'FARM') {
          setActiveTab('HISTORIAL');
        }
      } catch {}
    }

    // Load active session
    fetch('/api/auth/me')
      .then(r => r.json())
      .then(d => {
        if (d.authenticated && d.user) {
          setCurrentUser(d.user);
          localStorage.setItem('usf_user', JSON.stringify(d.user));
          if (d.user.role === 'FARM') {
            setActiveTab('HISTORIAL');
          }
        }
      })
      .catch(() => {})
      .finally(() => {
        fetchData('initial');
      });

    // Auto-refresh polling every 30 seconds - silent, only updates if new entries or edits detected
    const timer = setInterval(() => {
      fetchData('background');
    }, 30000);

    return () => clearInterval(timer);
  }, []);

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    fetchData('manual');
  };

  const handleClearFilters = () => {
    const emptyFilters = {
      masterCustomer: '',
      shipToCustomer: '',
      po: '',
      order: '',
      item: '',
      prodDesc: '',
      salidaFinca: '',
      shipdateMode: 'single' as const,
      shipdate: '',
      shipdateFrom: '',
      shipdateTo: '',
      deliverMode: 'single' as const,
      deliver: '',
      deliverFrom: '',
      deliverTo: '',
      farm: '',
      awb: '',
      agency: ''
    };
    setFilters(emptyFilters);
    filtersRef.current = emptyFilters;
    setExpandedGroups(new Set());
    setTimeout(() => {
      fetchData('manual');
    }, 20);
  };

  const toggleGroup = (groupKey: string) => {
    setExpandedGroups(prev => {
      const next = new Set(prev);
      if (next.has(groupKey)) next.delete(groupKey);
      else next.add(groupKey);
      return next;
    });
  };

  // Standard 3 USF boxes (EB, QB, HB)
  const USF_STANDARD_BOXES = [
    { code: 'EB-USF-104x15x15', label: 'EB-USF-104x15x15' },
    { code: 'QB-USF-104x15x10', label: 'QB-USF-104x15x10' },
    { code: 'HB-USF-104x20x15', label: 'HB-USF-104x20x15' },
  ];

  const normalizeBoxTypeCode = (val?: string | null): string => {
    if (!val) return 'EB-USF-104x15x15';
    const s = String(val).trim();
    if (s === '1' || s.toLowerCase() === 'eb') return 'EB-USF-104x15x15';
    if (s === '2' || s.toLowerCase() === 'qb') return 'QB-USF-104x15x10';
    if (s === '3' || s.toLowerCase() === 'hb') return 'HB-USF-104x20x15';
    return s;
  };

  // Returns all available box types: 3 USF standard boxes + ALL boxes belonging to target farm (not limited to 3)
  const getFilteredBoxTypesForFarm = (targetFarmId?: string | null, currentVal?: string) => {
    const normalizedVal = normalizeBoxTypeCode(currentVal);
    const usfItems = USF_STANDARD_BOXES.map(b => ({
      code: b.code,
      label: b.label,
      group: '📦 Cajas USF Estándar (3)'
    }));

    const farmItems: Array<{ code: string; label: string; group: string }> = [];
    if (targetFarmId) {
      const selectedFarmObj = farms.find(f => f.id === targetFarmId);
      const farmMatches = boxTypes.filter(b => {
        if (!b.code) return false;
        if (USF_STANDARD_BOXES.some(u => u.code.toLowerCase() === b.code.toLowerCase())) return false;
        if (['1', '2', '3'].includes(b.code)) return false;
        if (['EB', 'QB', 'HB', 'FB'].includes(b.code.toUpperCase())) return false;
        if (b.farmId && b.farmId === targetFarmId) return true;
        if (selectedFarmObj && b.farmName && b.farmName.trim().toLowerCase() === selectedFarmObj.name.trim().toLowerCase()) return true;
        return false;
      });

      const seenCodes = new Set<string>();
      for (const b of farmMatches) {
        if (!seenCodes.has(b.code)) {
          seenCodes.add(b.code);
          farmItems.push({
            code: b.code,
            label: b.name || b.code,
            group: '🌻 Cajas de Finca'
          });
        }
      }
    }

    const allOptions = [...usfItems, ...farmItems];
    if (normalizedVal && !allOptions.some(o => o.code === normalizedVal)) {
      allOptions.push({
        code: normalizedVal,
        label: normalizedVal,
        group: 'Otras'
      });
    }

    return allOptions;
  };

  // Add Item to "Place Order" Form from Summary Table
  const addItemToOrderForm = (group: SummaryGroup) => {
    setActiveTab('PEDIDOS');
    // Scroll to order form
    const orderFormEl = document.getElementById('place-order-section');
    if (orderFormEl) orderFormEl.scrollIntoView({ behavior: 'smooth' });

    // Check if already in lines
    const existingIdx = orderLinesForm.findIndex(l => l.itemCode === group.item && l.deliverDate === group.deliver);
    if (existingIdx >= 0) {
      alert(`El ítem ${group.item} ya está en la lista de compra actual.`);
      return;
    }

    const todayStr = new Date().toISOString().split('T')[0];
    const defaultDeparture = group.shipdt ? new Date(new Date(group.shipdt).getTime() - 86400000).toISOString().split('T')[0] : todayStr;
    const matchedProd = products.find(p => p.code === group.item);
    const defaultPrice = matchedProd?.declaredValue ?? 0;
    const defaultBoxType = normalizeBoxTypeCode(matchedProd?.boxType);

    setOrderLinesForm(prev => [
      ...prev,
      {
        itemCode: group.item,
        prodDesc: group.prodDesc,
        orderQty: group.totalFaltante,
        farmQty: Math.max(1, group.totalFaltante), // default to faltante or 1
        boxType: defaultBoxType,
        unitPrice: defaultPrice,
        farmDepartureDate: defaultDeparture,
        shipDate: group.shipdt || todayStr,
        deliverDate: group.deliver || ''
      }
    ]);
  };

  // Manually add blank item row to form
  const addBlankOrderLine = () => {
    const todayStr = new Date().toISOString().split('T')[0];
    setOrderLinesForm(prev => [
      ...prev,
      {
        itemCode: '',
        prodDesc: '',
        orderQty: 1,
        farmQty: 1,
        boxType: 'EB-USF-104x15x15',
        unitPrice: 0,
        farmDepartureDate: todayStr,
        shipDate: todayStr,
        deliverDate: ''
      }
    ]);
  };

  const updateOrderLineField = (index: number, field: keyof FarmOrderLineItem, value: any) => {
    setOrderLinesForm(prev => {
      const next = [...prev];
      next[index] = { ...next[index], [field]: value };
      if (field === 'itemCode') {
        const prod = products.find(p => p.code === value);
        if (prod) {
          next[index].prodDesc = prod.name;
          next[index].boxType = normalizeBoxTypeCode(prod.boxType);
          if (prod.declaredValue !== undefined && prod.declaredValue !== null) {
            next[index].unitPrice = prod.declaredValue;
          }
        }
      }
      return next;
    });
  };

  const removeOrderLine = (index: number) => {
    setOrderLinesForm(prev => prev.filter((_, i) => i !== index));
  };

  // Handle PLACE ORDER Submit
  const handlePlaceOrder = async () => {
    if (!selectedFarmId) {
      alert('Por favor selecciona una Finca para realizar el pedido.');
      return;
    }
    if (!selectedAwb.trim()) {
      alert('Por favor ingresa o selecciona la AWB (Guía Aérea).');
      return;
    }
    if (orderLinesForm.length === 0) {
      alert('Agrega al menos un ítem para realizar el pedido.');
      return;
    }

    // Validate quantities and prices
    for (const line of orderLinesForm) {
      if (!line.itemCode) {
        alert('Hay líneas sin código de producto seleccionado.');
        return;
      }
      if (line.farmQty <= 0) {
        alert(`La cantidad para el ítem ${line.itemCode} debe ser mayor a 0.`);
        return;
      }
    }

    setPlacingOrder(true);
    try {
      const payload = {
        farmId: selectedFarmId,
        agency: selectedAgency,
        awb: selectedAwb.trim(),
        hawb: `FC-${new Date().getFullYear()}`,
        items: orderLinesForm
      };

      const res = await fetch('/api/pedidos/place-order', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al procesar pedido a finca');

      const selectedFarm = farms.find(f => f.id === selectedFarmId);

      // Trigger automatic download of Excel file for Farm
      exportFarmExcel(selectedFarm, payload.items, payload.awb, payload.agency);

      // Open success modal
      setOrderSuccessModal({
        message: data.message,
        notice: data.farmNotice,
        lineIds: data.assignedLineIds || [],
        details: data.purchaseDetails || []
      });

      // Clear form & refresh summary
      setOrderLinesForm([]);
      fetchData();
    } catch (err: any) {
      alert(`Error: ${err.message}`);
    } finally {
      setPlacingOrder(false);
    }
  };

  // Helper para formatear AWB completo (ej. 123-8547-8523 - FEDEX - SHIPDATE 2026-10-01)
  const getFormattedAwbDisplay = (awbVal: string, agencyVal: string) => {
    if (!awbVal) return '—';
    const digits = awbVal.replace(/\D/g, '');
    const formattedAwb = digits.length === 11
      ? `${digits.slice(0, 3)}-${digits.slice(3, 7)}-${digits.slice(7)}`
      : (digits.length === 8 ? `${digits.slice(0, 4)}-${digits.slice(4)}` : awbVal);

    const matchedG = guias.find(g => g.awb.trim() === awbVal.trim());
    const ag = (matchedG?.agency || agencyVal || 'FEDEX').toUpperCase();
    const ship = matchedG?.shipDate
      ? formatDateToYYYYMMDD(matchedG.shipDate)
      : (orderLinesForm[0]?.shipDate || '');

    return ship ? `${formattedAwb} - ${ag} - SHIPDATE ${ship}` : `${formattedAwb} - ${ag}`;
  };

  // Export Farm Excel summary
  const exportFarmExcel = (farm: Farm | undefined, items: FarmOrderLineItem[], awb: string, agency: string) => {
    const farmName = farm?.name || 'FINCA';
    const rows = items.map(item => ({
      'ITEM': item.itemCode,
      'DESCRIPCION': item.prodDesc,
      'BOX TYPE': item.boxType,
      'CANTIDAD (CAJAS)': item.farmQty,
      'PRECIO UNITARIO ($)': item.unitPrice.toFixed(2),
      'PRECIO TOTAL ($)': (item.farmQty * item.unitPrice).toFixed(2),
      'SALIDA FINCA': item.farmDepartureDate,
      'SHIPDATE': item.shipDate,
      'DELIVERY': item.deliverDate,
      'AGENCIA': agency,
      'AWB': awb,
      'FECHA PEDIDO': new Date().toLocaleString('es-EC')
    }));

    const ws = XLSX.utils.json_to_sheet(rows);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Pedido Finca');
    XLSX.writeFile(wb, `PEDIDO_${farmName.replace(/\s+/g, '_')}_${awb}_${new Date().toISOString().split('T')[0]}.xlsx`);
  };

  // Guías management
  const openNewGuiaModal = () => {
    setGuiaEditingId(null);
    setGuiaForm({
      agency: 'FEDEX',
      deliverDate: new Date().toISOString().split('T')[0],
      shipDate: new Date().toISOString().split('T')[0],
      awb: '',
      master: '',
      notes: ''
    });
    setGuiaError('');
    setGuiaModalOpen(true);
  };

  const openEditGuiaModal = (g: AirwayBill) => {
    setGuiaEditingId(g.id);
    setGuiaForm({
      agency: g.agency,
      deliverDate: formatDateToYYYYMMDD(g.deliverDate),
      shipDate: formatDateToYYYYMMDD(g.shipDate),
      awb: g.awb,
      master: g.master,
      notes: g.notes || ''
    });
    setGuiaError('');
    setGuiaModalOpen(true);
  };

  const handleGuiaAwbChange = (val: string) => {
    const cleanAwb = val.trim();
    const digitsOnly = cleanAwb.replace(/\D/g, '');
    const autoMaster = digitsOnly.length >= 4 ? digitsOnly.slice(-4) : cleanAwb.slice(-4);
    setGuiaForm(prev => ({ ...prev, awb: val, master: autoMaster }));
  };

  const handleSaveGuia = async (e: React.FormEvent) => {
    e.preventDefault();
    setSavingGuia(true);
    setGuiaError('');
    try {
      const url = guiaEditingId ? `/api/guias/${guiaEditingId}` : '/api/guias';
      const method = guiaEditingId ? 'PUT' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(guiaForm)
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al guardar guía');
      setGuiaModalOpen(false);
      fetchData();
    } catch (err: any) {
      setGuiaError(err.message);
    } finally {
      setSavingGuia(false);
    }
  };

  // Derived active/archived guías and agencies
  const activeGuias = useMemo(() => guias.filter(g => g.status !== 'ARCHIVED'), [guias]);
  const archivedGuias = useMemo(() => guias.filter(g => g.status === 'ARCHIVED'), [guias]);
  const activeAgencies = useMemo(() => {
    const set = new Set<string>();
    activeGuias.forEach(g => {
      if (g.agency) set.add(g.agency.trim().toUpperCase());
    });
    return Array.from(set).sort();
  }, [activeGuias]);

  // Keep selectedAgency in sync with available active agencies
  useEffect(() => {
    if (activeAgencies.length > 0 && !activeAgencies.includes(selectedAgency)) {
      setSelectedAgency(activeAgencies[0]);
    }
  }, [activeAgencies, selectedAgency]);

  const displayedGuias = useMemo(() => {
    if (guiaViewMode === 'ACTIVE') return activeGuias;
    if (guiaViewMode === 'ARCHIVED') return archivedGuias;
    return guias;
  }, [guiaViewMode, activeGuias, archivedGuias, guias]);

  const handleArchiveGuia = async (id: string, archive: boolean) => {
    const actionLabel = archive ? 'archivar' : 'desarchivar';
    const guiaTarget = guias.find(g => g.id === id);
    const awbLabel = guiaTarget ? guiaTarget.awb : 'esta guía';
    if (!window.confirm(`¿Estás seguro de ${actionLabel} la guía aérea ${awbLabel}? ${archive ? 'Ya no se podrá seleccionar para nuevos pedidos.' : 'Volverá a estar activa para nuevos pedidos.'}`)) return;
    try {
      const res = await fetch(`/api/guias/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: archive ? 'ARCHIVED' : 'ACTIVE' })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || `Error al ${actionLabel} guía`);
      setSelectedGuiaIds(prev => {
        const next = new Set(prev);
        next.delete(id);
        return next;
      });
      fetchData();
    } catch (err: any) {
      alert(`Error: ${err.message}`);
    }
  };

  const handleBulkArchiveGuias = async (archive: boolean) => {
    if (selectedGuiaIds.size === 0) return;
    const actionLabel = archive ? 'archivar' : 'desarchivar';
    if (!window.confirm(`¿Estás seguro de ${actionLabel} las ${selectedGuiaIds.size} guía(s) aérea(s) seleccionadas?`)) return;
    try {
      const res = await fetch('/api/guias/archive', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ids: Array.from(selectedGuiaIds),
          status: archive ? 'ARCHIVED' : 'ACTIVE'
        })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || `Error al ${actionLabel} guías`);
      setSelectedGuiaIds(new Set());
      fetchData();
    } catch (err: any) {
      alert(`Error: ${err.message}`);
    }
  };

  const toggleSelectAllGuias = () => {
    if (selectedGuiaIds.size === displayedGuias.length && displayedGuias.length > 0) {
      setSelectedGuiaIds(new Set());
    } else {
      setSelectedGuiaIds(new Set(displayedGuias.map(g => g.id)));
    }
  };

  const toggleSelectGuia = (id: string) => {
    setSelectedGuiaIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const handleDeleteGuia = async (id: string) => {
    if (!window.confirm('¿Eliminar esta Guía Aérea permanentemente?')) return;
    try {
      const res = await fetch(`/api/guias/${id}`, { method: 'DELETE' });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al eliminar guía');
      fetchData();
    } catch (err: any) {
      alert(`Error: ${err.message}`);
    }
  };

  const isFarmUser = currentUser?.role === 'FARM';

  // Historial data, filters and grouping strictly scoped to Farm if role is FARM
  const purchasedLines = useMemo(() => {
    return flatLines.filter(l => {
      if (!l.farmId) return false;
      if (isFarmUser) {
        const matchId = currentUser?.farmId && l.farmId === currentUser.farmId;
        const matchName = currentUser?.farmName && l.farmName && l.farmName.trim().toLowerCase() === currentUser.farmName.trim().toLowerCase();
        return matchId || matchName;
      }
      return true;
    });
  }, [flatLines, isFarmUser, currentUser]);

  const displayedRejections = useMemo(() => {
    return rejections.filter(r => {
      if (isFarmUser) {
        const matchId = currentUser?.farmId && r.farmId === currentUser.farmId;
        const matchName = currentUser?.farmName && r.farm?.name && r.farm.name.trim().toLowerCase() === currentUser.farmName.trim().toLowerCase();
        return matchId || matchName;
      }
      return true;
    });
  }, [rejections, isFarmUser, currentUser]);

  const displayedCancelledLabels = useMemo(() => {
    return cancelledLabels.filter(c => {
      if (isFarmUser) {
        const matchId = currentUser?.farmId && c.farmId === currentUser.farmId;
        const matchName = currentUser?.farmName && c.farmName && c.farmName.trim().toLowerCase() === currentUser.farmName.trim().toLowerCase();
        return matchId || matchName;
      }
      return true;
    });
  }, [cancelledLabels, isFarmUser, currentUser]);

  const handleApplyHistorialFilters = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    setAppliedHistorialFilters({ ...historialFilters });
  };

  const handleClearHistorialFilters = () => {
    const emptyFilters = {
      customer: '',
      farmId: '',
      item: '',
      prodDesc: '',
      price: '',
      departureDate: '',
      deliverDate: '',
      agency: '',
      awb: ''
    };
    setHistorialFilters(emptyFilters);
    setAppliedHistorialFilters(emptyFilters);
  };

  const activeHistorialFilterCount = useMemo(() => {
    return Object.values(appliedHistorialFilters).filter(v => Boolean(v && String(v).trim())).length;
  }, [appliedHistorialFilters]);

  const filteredPurchasedLines = useMemo(() => {
    return purchasedLines.filter(line => {
      if (appliedHistorialFilters.customer) {
        const cText = `${line.customerName || ''} ${line.masterName || ''} ${line.shippingName || ''} ${line.po || ''}`.toLowerCase();
        if (!cText.includes(appliedHistorialFilters.customer.toLowerCase())) return false;
      }
      if (appliedHistorialFilters.farmId && line.farmId !== appliedHistorialFilters.farmId) return false;
      if (appliedHistorialFilters.item && !line.item.toLowerCase().includes(appliedHistorialFilters.item.toLowerCase())) return false;
      if (appliedHistorialFilters.prodDesc && !line.prodDesc.toLowerCase().includes(appliedHistorialFilters.prodDesc.toLowerCase())) return false;
      if (appliedHistorialFilters.price) {
        const numPrice = parseFloat(appliedHistorialFilters.price);
        if (!isNaN(numPrice) && Math.abs((line.farmPrice || 0) - numPrice) > 0.01) return false;
      }
      if (appliedHistorialFilters.departureDate && line.farmDepartureDate !== appliedHistorialFilters.departureDate) return false;
      if (appliedHistorialFilters.deliverDate && line.deliver !== appliedHistorialFilters.deliverDate) return false;
      if (appliedHistorialFilters.agency) {
        const ag = (line.agency || '').toLowerCase();
        if (!ag.includes(appliedHistorialFilters.agency.toLowerCase())) return false;
      }
      if (appliedHistorialFilters.awb) {
        const aw = (line.awb || '').toLowerCase();
        if (!aw.includes(appliedHistorialFilters.awb.toLowerCase())) return false;
      }
      return true;
    });
  }, [purchasedLines, appliedHistorialFilters]);

  // Grouped by customer (if admin), farm, item, departureDate, shipDate, deliverDate (if admin), agency, awb
  // Grouped by farm, item, boxtype, departureDate, shipDate, deliverDate, agency, awb, price (Cliente and OrderDate removed per UI requirements)
  const historialGroups = useMemo(() => {
    const groupsMap = new Map<string, HistorialGroup>();

    filteredPurchasedLines.forEach(line => {
      const farmKey = line.farmName || line.farmId || '—';
      const key = `${farmKey}___${line.item}___${line.boxType || ''}___${line.farmDepartureDate || ''}___${line.shipdt || ''}___${line.deliver || ''}___${line.agency || ''}___${line.awb || ''}___${line.farmPrice || 0}`;

      if (!groupsMap.has(key)) {
        groupsMap.set(key, {
          groupKey: key,
          customerName: line.customerName || '—',
          pos: line.po ? [line.po] : [],
          farmId: line.farmId || '',
          farmName: line.farmName || '—',
          item: line.item,
          prodDesc: line.prodDesc,
          farmPrice: line.farmPrice || 0,
          orddate: line.orddate || '',
          farmDepartureDate: line.farmDepartureDate || '',
          shipdt: line.shipdt || '',
          deliver: line.deliver || '',
          agency: line.agency || '—',
          awb: line.awb || '—',
          boxType: line.boxType || 'QB',
          status: line.status,
          lines: [],
          lineIds: [],
          qtyActual: 0,
          cancelledCount: 0,
          qtyOrdered: 0,
          boxNumbers: [],
          uniqueCodes: []
        });
      }

      const g = groupsMap.get(key)!;
      g.lines.push(line);
      g.lineIds.push(line.id);
      g.qtyActual += line.qty || 1;
      if (line.orddate && (!g.orddate || line.orddate < g.orddate)) {
        g.orddate = line.orddate;
      }
      if (line.po && !g.pos.includes(line.po)) g.pos.push(line.po);
      if (line.boxNumber && !g.boxNumbers.includes(line.boxNumber)) g.boxNumbers.push(line.boxNumber);
      if (line.uniqueCode && !g.uniqueCodes.includes(line.uniqueCode)) g.uniqueCodes.push(line.uniqueCode);
    });

    const groups = Array.from(groupsMap.values());
    // Correlate cancelled labels with groups to display original ordered count and cancelled badge
    groups.forEach(g => {
      const matchingCancelled = cancelledLabels.filter(c => {
        const itemMatch = c.itemCode?.toLowerCase() === g.item?.toLowerCase();
        const farmMatch = !g.farmId || c.farmId === g.farmId || (c.farmName && c.farmName.toLowerCase() === g.farmName.toLowerCase());
        const awbMatch = !g.awb || g.awb === '—' || (c.airwayBill && c.airwayBill.trim().toLowerCase() === g.awb.trim().toLowerCase());
        return itemMatch && farmMatch && awbMatch;
      });

      g.cancelledCount = matchingCancelled.length;
      g.qtyOrdered = g.qtyActual + g.cancelledCount;
    });

    return groups;
  }, [filteredPurchasedLines, cancelledLabels]);

  // Dispatches grouping for Tab 3 (Grouping by Finca + Salida Finca + Agencia + Guía AWB)
  const historialDispatchGroups = useMemo(() => {
    const dispatchMap = new Map<string, {
      key: string;
      farmId: string;
      farmName: string;
      farmDepartureDate: string;
      shipdt: string;
      agency: string;
      awb: string;
      totalBoxes: number;
      totalPrice: number;
      lineIds: string[];
      printableLineIds: string[];
      allReceived: boolean;
      hasReceived: boolean;
      groups: HistorialGroup[];
      individualLines: SummaryLine[];
    }>();

    // Helper to check if line is already received in cold room / shipped
    const isLineReceived = (l: { status?: string; received?: number }) => {
      const st = (l.status || '').toUpperCase();
      return st === 'RECEIVED' || st === 'RECIBIDO' || st === 'SHIPPED' || ((l.received || 0) > 0);
    };

    if (historialViewMode === 'GROUPED') {
      historialGroups.forEach(g => {
        const farmKey = g.farmName || g.farmId || 'Sin Finca';
        const dKey = `${farmKey}___${g.farmDepartureDate || 'Sin Fecha'}___${g.agency || 'Sin Agencia'}___${g.awb || 'Sin AWB'}`;
        if (!dispatchMap.has(dKey)) {
          dispatchMap.set(dKey, {
            key: dKey,
            farmId: g.farmId,
            farmName: g.farmName || '—',
            farmDepartureDate: g.farmDepartureDate || '—',
            shipdt: g.shipdt || '—',
            agency: g.agency || '—',
            awb: g.awb || '—',
            totalBoxes: 0,
            totalPrice: 0,
            lineIds: [],
            printableLineIds: [],
            allReceived: false,
            hasReceived: false,
            groups: [],
            individualLines: []
          });
        }
        const d = dispatchMap.get(dKey)!;
        d.groups.push(g);
        d.totalBoxes += g.qtyActual;
        d.totalPrice += g.qtyActual * (g.farmPrice || 0);
        d.lineIds.push(...g.lineIds);
        if ((!d.shipdt || d.shipdt === '—') && g.shipdt) d.shipdt = g.shipdt;
      });
    } else {
      filteredPurchasedLines.forEach(l => {
        const farmKey = l.farmName || l.farmId || 'Sin Finca';
        const dKey = `${farmKey}___${l.farmDepartureDate || 'Sin Fecha'}___${l.agency || 'Sin Agencia'}___${l.awb || 'Sin AWB'}`;
        if (!dispatchMap.has(dKey)) {
          dispatchMap.set(dKey, {
            key: dKey,
            farmId: l.farmId || '',
            farmName: l.farmName || '—',
            farmDepartureDate: l.farmDepartureDate || '—',
            shipdt: l.shipdt || '—',
            agency: l.agency || '—',
            awb: l.awb || '—',
            totalBoxes: 0,
            totalPrice: 0,
            lineIds: [],
            printableLineIds: [],
            allReceived: false,
            hasReceived: false,
            groups: [],
            individualLines: []
          });
        }
        const d = dispatchMap.get(dKey)!;
        d.individualLines.push(l);
        d.totalBoxes += (l.qty || 1);
        d.totalPrice += (l.qty || 1) * (l.farmPrice || 0);
        d.lineIds.push(l.id);
        if ((!d.shipdt || d.shipdt === '—') && l.shipdt) d.shipdt = l.shipdt;
      });
    }

    // Line lookup to compute printable lines (excluding received lines)
    const lineMap = new Map<string, SummaryLine>();
    filteredPurchasedLines.forEach(l => lineMap.set(l.id, l));

    dispatchMap.forEach(d => {
      d.printableLineIds = d.lineIds.filter(id => {
        const line = lineMap.get(id);
        return line ? !isLineReceived(line) : true;
      });
      d.allReceived = d.lineIds.length > 0 && d.printableLineIds.length === 0;
      d.hasReceived = d.printableLineIds.length < d.lineIds.length;
    });

    const dispatches = Array.from(dispatchMap.values());

    // Sort chronologically ASC from oldest date to newest date (e.g. 2026-09-28 before 2026-09-29 before 2026-09-30)
    dispatches.sort((a, b) => {
      const dateA = a.farmDepartureDate && a.farmDepartureDate !== '—' ? a.farmDepartureDate : (a.shipdt || '9999-99-99');
      const dateB = b.farmDepartureDate && b.farmDepartureDate !== '—' ? b.farmDepartureDate : (b.shipdt || '9999-99-99');
      if (dateA !== dateB) return dateA.localeCompare(dateB);
      if (a.farmName !== b.farmName) return a.farmName.localeCompare(b.farmName);
      return a.awb.localeCompare(b.awb);
    });

    return dispatches;
  }, [historialViewMode, historialGroups, filteredPurchasedLines]);

  const toggleSelectAllHistorial = () => {
    const activeIds = historialViewMode === 'GROUPED'
      ? historialGroups.flatMap(g => g.lineIds)
      : filteredPurchasedLines.map(l => l.id);

    if (activeIds.length > 0 && selectedHistorialIds.size >= activeIds.length) {
      setSelectedHistorialIds(new Set());
    } else {
      setSelectedHistorialIds(new Set(activeIds));
    }
  };

  const toggleSelectHistorialLine = (id: string) => {
    setSelectedHistorialIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const toggleSelectHistorialGroup = (lineIds: string[]) => {
    setSelectedHistorialIds(prev => {
      const next = new Set(prev);
      const allSelected = lineIds.every(id => next.has(id));
      if (allSelected) {
        lineIds.forEach(id => next.delete(id));
      } else {
        lineIds.forEach(id => next.add(id));
      }
      return next;
    });
  };

  const handleCancelHistorialLines = async (lineIds: string[]) => {
    if (lineIds.length === 0) return;
    const confirmMsg = lineIds.length === 1
      ? '¿Está seguro de cancelar esta orden/caja? Regresará a estado PENDIENTE (NEW) para ser asignada nuevamente y su código quedará registrado como CANCELADO.'
      : `¿Está seguro de cancelar las ${lineIds.length} órdenes/cajas seleccionadas? Regresarán a estado PENDIENTE (NEW) para ser asignadas nuevamente y sus códigos quedarán registrados como CANCELADOS.`;
    if (!window.confirm(confirmMsg)) return;

    try {
      const res = await fetch('/api/pedidos/manage-lines', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'cancel', lineIds })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al cancelar cajas');
      alert(data.message || 'Cajas canceladas exitosamente.');
      setSelectedHistorialIds(prev => {
        const next = new Set(prev);
        lineIds.forEach(id => next.delete(id));
        return next;
      });
      fetchData();
    } catch (err: any) {
      alert(`Error: ${err.message}`);
    }
  };

  // Open multi-edit modal from grouped lines or multiple checkboxes
  const handleOpenEditFromGroups = (groupsToEdit: HistorialGroup[]) => {
    if (groupsToEdit.length === 0) return;
    const items: EditModalItem[] = groupsToEdit.map(g => ({
      id: g.groupKey,
      lineIds: g.lineIds,
      orderedQty: g.qtyActual,
      newQty: g.qtyActual,
      productId: products.find(p => p.code === g.item)?.id || '',
      productCode: g.item,
      productName: g.prodDesc,
      farmId: g.farmId,
      farmName: g.farmName,
      farmPrice: g.farmPrice || 40.00,
      farmDepartureDate: g.farmDepartureDate || new Date().toISOString().split('T')[0],
      boxType: g.boxType || 'QB',
      airwayBill: g.awb !== '—' ? g.awb : '',
      agency: g.agency !== '—' ? g.agency : ''
    }));

    setMultiEditModal({
      isOpen: true,
      title: items.length === 1
        ? `Editar Orden: ${items[0].productCode} (${items[0].productName})`
        : `Editar ${items.length} Productos Seleccionados Simutáneamente`,
      items
    });
  };

  const handleOpenEditFromLines = (lineIds: string[]) => {
    if (lineIds.length === 0) return;
    // Group selected lines by item code
    const lines = purchasedLines.filter(l => lineIds.includes(l.id));
    const byItem = new Map<string, SummaryLine[]>();
    lines.forEach(l => {
      const k = `${l.item}___${l.farmId || ''}`;
      if (!byItem.has(k)) byItem.set(k, []);
      byItem.get(k)!.push(l);
    });

    const items: EditModalItem[] = Array.from(byItem.entries()).map(([k, groupLines]) => {
      const first = groupLines[0];
      return {
        id: k,
        lineIds: groupLines.map(l => l.id),
        orderedQty: groupLines.length,
        newQty: groupLines.length,
        productId: products.find(p => p.code === first.item)?.id || '',
        productCode: first.item,
        productName: first.prodDesc,
        farmId: first.farmId || '',
        farmName: first.farmName || '',
        farmPrice: first.farmPrice || 40.00,
        farmDepartureDate: first.farmDepartureDate || new Date().toISOString().split('T')[0],
        boxType: first.boxType || 'QB',
        airwayBill: first.awb && first.awb !== '—' ? first.awb : '',
        agency: first.agency && first.agency !== '—' ? first.agency : ''
      };
    });

    setMultiEditModal({
      isOpen: true,
      title: items.length === 1
        ? `Editar Orden: ${items[0].productCode} (${items[0].productName})`
        : `Editar ${items.length} Productos Seleccionados Simultáneamente`,
      items
    });
  };

  const updateMultiEditItem = (index: number, field: keyof EditModalItem, value: any) => {
    if (!multiEditModal) return;
    const newItems = [...multiEditModal.items];
    newItems[index] = { ...newItems[index], [field]: value };
    if (field === 'productId') {
      const prod = products.find(p => p.id === value);
      if (prod) {
        newItems[index].productCode = prod.code;
        newItems[index].productName = prod.name;
        if (prod.boxType) newItems[index].boxType = prod.boxType;
      }
    }
    if (field === 'farmId') {
      const f = farms.find(farm => farm.id === value);
      if (f) {
        newItems[index].farmName = f.name;
      }
    }
    setMultiEditModal({
      ...multiEditModal,
      items: newItems
    });
  };

  const handleSaveMultiEdit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!multiEditModal || multiEditModal.items.length === 0) return;
    setSavingLineAction(true);
    try {
      const res = await fetch('/api/pedidos/manage-lines', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'edit',
          items: multiEditModal.items
        })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al actualizar órdenes');
      alert(data.message || 'Órdenes actualizadas exitosamente.');
      setMultiEditModal(null);
      setSelectedHistorialIds(new Set());
      fetchData();
    } catch (err: any) {
      alert(`Error: ${err.message}`);
    } finally {
      setSavingLineAction(false);
    }
  };


  const handleExportSummaryExcel = () => {
    if (flatLines.length === 0) {
      alert('No hay datos en el resumen para exportar con los filtros actuales.');
      return;
    }
    const data = flatLines.map(line => ({
      'PO': line.po || '',
      'Orden': line.orderNumber || '',
      'Ítem': line.item || '',
      'Descripción': line.prodDesc || '',
      'Fecha Orden': line.orddate || '',
      'Ship Date': line.shipdt || '',
      'Delivery': line.deliver || '',
      'Cantidad': line.qty || 0,
      'Asignado Finca': line.farmAssigned || 0,
      'Recibido Frío': line.received || 0,
      'Faltante': line.faltante || 0,
      'Estado': line.status || '',
      'Cliente Master': line.masterName || '',
      'Cliente Destino': line.customerName || '',
      'Finca Asignada': line.farmName || '',
      'Guía AWB': line.awb || '',
      'Agencia': line.agency || ''
    }));
    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Resumen Pedidos');
    XLSX.writeFile(wb, `Resumen_Pedidos_${new Date().toISOString().split('T')[0]}.xlsx`);
  };

  const handleExportGuiasExcel = () => {
    if (displayedGuias.length === 0) {
      alert('No hay guías aéreas para exportar.');
      return;
    }
    const data = displayedGuias.map(g => ({
      'Agencia': g.agency,
      'Delivery Date': formatDateToYYYYMMDD(g.deliverDate),
      'Ship Date': formatDateToYYYYMMDD(g.shipDate),
      'AWB': g.awb,
      'Master (4 Dígitos)': g.master,
      'Estado': g.status,
      'Notas': g.notes || ''
    }));
    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Guias Aereas');
    XLSX.writeFile(wb, `Guias_Aereas_${new Date().toISOString().split('T')[0]}.xlsx`);
  };

  const handleExportHistorialExcel = () => {
    if (filteredPurchasedLines.length === 0) {
      alert('No hay compras registradas para exportar con los filtros actuales.');
      return;
    }

    // Exact purchase order format requested:
    // ITEM | DESCRIPCION | BOX TYPE | CANTIDAD (CAJAS) | PRECIO UNITARIO ($) | PRECIO TOTAL ($) | SALIDA FINCA | SHIPDATE | DELIVERY | AGENCIA | AWB | FECHA PEDIDO
    const aggregatedMap = new Map<string, {
      itemCode: string;
      prodDesc: string;
      boxType: string;
      qty: number;
      unitPrice: number;
      farmDepartureDate: string;
      shipDate: string;
      deliverDate: string;
      agency: string;
      awb: string;
      orderDate: string;
      farmName: string;
    }>();

    filteredPurchasedLines.forEach(line => {
      const key = `${line.item}___${line.boxType || ''}___${line.farmDepartureDate || ''}___${line.shipdt || ''}___${line.deliver || ''}___${line.agency || ''}___${line.awb || ''}___${line.farmPrice || 0}`;
      if (!aggregatedMap.has(key)) {
        aggregatedMap.set(key, {
          itemCode: line.item || '',
          prodDesc: line.prodDesc || '',
          boxType: line.boxType || 'QB',
          qty: 0,
          unitPrice: line.farmPrice || 0,
          farmDepartureDate: line.farmDepartureDate || '',
          shipDate: line.shipdt || '',
          deliverDate: line.deliver || '',
          agency: line.agency || '',
          awb: line.awb || '',
          orderDate: line.orddate || '',
          farmName: line.farmName || ''
        });
      }
      const agg = aggregatedMap.get(key)!;
      agg.qty += (line.qty || 1);
    });

    const rows = Array.from(aggregatedMap.values()).map(r => ({
      'ITEM': r.itemCode,
      'DESCRIPCION': r.prodDesc,
      'BOX TYPE': r.boxType,
      'CANTIDAD (CAJAS)': r.qty,
      'PRECIO UNITARIO ($)': Number(r.unitPrice.toFixed(2)),
      'PRECIO TOTAL ($)': Number((r.qty * r.unitPrice).toFixed(2)),
      'SALIDA FINCA': r.farmDepartureDate,
      'SHIPDATE': r.shipDate,
      'DELIVERY': r.deliverDate,
      'AGENCIA': r.agency,
      'AWB': r.awb,
      'FECHA PEDIDO': r.orderDate || new Date().toISOString().split('T')[0]
    }));

    const ws = XLSX.utils.json_to_sheet(rows);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Pedido Finca');
    XLSX.writeFile(wb, `PEDIDO_FINCA_${new Date().toISOString().split('T')[0]}.xlsx`);
  };

  const handleExportRejectionsExcel = () => {
    if (displayedRejections.length === 0) {
      alert('No hay rechazos QC para exportar.');
      return;
    }
    const data = displayedRejections.map(r => ({
      'Finca': r.farm?.name || '—',
      'RUC Finca': r.farm?.ruc || '—',
      'Fecha Rechazo': new Date(r.createdAt).toLocaleString('es-EC'),
      'Box Number': r.boxNumber || '—',
      'Código Producto': r.productCode || '—',
      'Producto': r.productName || '—',
      'Motivo': r.reason || '',
      'Valor Descuento ($)': r.price || 0,
      'Crédito Aplicado': r.creditApplied ? 'SÍ' : 'NO'
    }));
    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Rechazos QC');
    XLSX.writeFile(wb, `Rechazos_QC_${new Date().toISOString().split('T')[0]}.xlsx`);
  };

  const handleExportCancelledExcel = () => {
    const filtered = displayedCancelledLabels.filter(c => {
      if (!historialSearchCancelled) return true;
      const q = historialSearchCancelled.toLowerCase();
      return `${c.uniqueCode} ${c.boxNumber} ${c.itemCode} ${c.productName} ${c.farmName || ''} ${c.customerName || ''} ${c.po || ''} ${c.airwayBill || ''}`.toLowerCase().includes(q);
    });
    if (filtered.length === 0) {
      alert('No hay etiquetas canceladas para exportar.');
      return;
    }
    const data = filtered.map(c => ({
      'Código Único': c.uniqueCode,
      'Box Number': c.boxNumber,
      'Tipo Caja': c.boxType || '',
      'Ítem': c.itemCode,
      'Producto': c.productName,
      'Finca': c.farmName || '—',
      'Cliente': c.customerName || '—',
      'PO': c.po || '',
      'Guía AWB': c.airwayBill || '—',
      'Agencia': c.agency || '—',
      'Precio Finca ($)': c.farmPrice || 0,
      'Salida Finca': c.farmDepartureDate || '',
      'Fecha Cancelación': new Date(c.cancelledAt).toLocaleString('es-EC'),
      'Motivo': c.reason || 'Cancelación de orden'
    }));
    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Etiquetas Canceladas');
    XLSX.writeFile(wb, `Etiquetas_Canceladas_${new Date().toISOString().split('T')[0]}.xlsx`);
  };

  const selectedFarmObj = farms.find(f => f.id === selectedFarmId);

  return (
    <MainLayout>
      <div style={{ padding: '1.5rem', maxWidth: '1600px', margin: '0 auto' }}>
        {/* Top Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', flexWrap: 'wrap', gap: '1rem' }}>
          <div>
            <h1 style={{ margin: 0, fontSize: '1.8rem', fontWeight: 800, color: '#1c5236' }}>
              {isFarmUser
                ? `🌻 Portal Finca • ${currentUser?.farmName || 'Mi Finca'}`
                : '🛒 Módulo de Pedidos a Fincas y Asignación de Guías'}
            </h1>
            <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.9rem' }}>
              {isFarmUser
                ? 'Historial de compras asignadas, rechazos de calidad y descarga de etiquetas para cajas.'
                : 'Resumen de órdenes por fecha de entrega e ítem, colocación de pedidos con prioridad FIFO, códigos únicos y control de faltantes.'}
            </p>
          </div>
          <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
            {/* Botón de Actualizar Instantáneamente */}
            <button
              type="button"
              onClick={() => fetchData(true)}
              disabled={refreshing}
              style={{
                display: 'flex', alignItems: 'center', gap: '0.5rem',
                background: '#f8fafc', border: '1px solid #cbd5e1', borderRadius: '8px',
                padding: '0.65rem 1.1rem', fontWeight: 700, fontSize: '0.88rem', color: '#334155',
                cursor: refreshing ? 'not-allowed' : 'pointer', transition: 'all 0.2s ease',
                boxShadow: '0 2px 5px rgba(0,0,0,0.04)'
              }}
              title="Actualizar datos de las tablas instantáneamente"
            >
              <svg
                width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                style={{ animation: refreshing ? 'spin 0.8s linear infinite' : 'none' }}
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              {refreshing ? 'Actualizando...' : 'Actualizar Información'}
            </button>

            {!isFarmUser && (
              <>
                <button
                  onClick={() => setActiveTab('GUIAS')}
                  style={{ padding: '0.65rem 1.25rem', borderRadius: '8px', border: '1px solid #1c5236', background: activeTab === 'GUIAS' ? '#1c5236' : '#fff', color: activeTab === 'GUIAS' ? '#fff' : '#1c5236', fontWeight: 700, cursor: 'pointer', fontSize: '0.88rem' }}
                >
                  ✈️ Asignación Guías (Paso 2)
                </button>
                <button
                  onClick={() => {
                    const el = document.getElementById('place-order-section');
                    if (el) el.scrollIntoView({ behavior: 'smooth' });
                  }}
                  style={{ padding: '0.65rem 1.4rem', borderRadius: '8px', border: 'none', background: 'linear-gradient(135deg, #1c5236, #2d6a4f)', color: '#fff', fontWeight: 700, cursor: 'pointer', fontSize: '0.88rem', boxShadow: '0 4px 12px rgba(28,82,54,0.25)' }}
                >
                  + Hacer Pedido Finca
                </button>
              </>
            )}
          </div>
        </div>

        {/* Navigation Tabs (Filtered for farm user to tabs 3, 4, 5 only) */}
        <div style={{ display: 'flex', gap: '0.5rem', borderBottom: '2px solid #e5e7eb', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
          {[
            { id: 'PEDIDOS', label: '1. Resumen y Pedidos Fincas', icon: '📊' },
            { id: 'GUIAS', label: '2. Asignación de Guías Aéreas', icon: '✈️' },
            { id: 'HISTORIAL', label: '3. Historial de Compras', icon: '📋' },
            { id: 'RECHAZOS', label: '4. Rechazos QC y Ajustes', icon: '⚠️' },
            { id: 'CANCELADAS', label: '5. Etiquetas Canceladas', icon: '🚫', count: displayedCancelledLabels.length }
          ]
            .filter(tab => !isFarmUser || ['HISTORIAL', 'RECHAZOS', 'CANCELADAS'].includes(tab.id))
            .map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as any)}
                style={{
                  padding: '0.75rem 1.4rem',
                  border: 'none',
                  borderBottom: activeTab === tab.id ? '3px solid #1c5236' : '3px solid transparent',
                  background: 'transparent',
                  color: activeTab === tab.id ? '#1c5236' : '#6b7280',
                  fontWeight: activeTab === tab.id ? 800 : 600,
                  fontSize: '0.95rem',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.45rem'
                }}
              >
                <span>{tab.icon}</span>
                {tab.label}
                {tab.count !== undefined && tab.count > 0 && (
                  <span style={{ background: '#fee2e2', color: '#dc2626', padding: '0.12rem 0.45rem', borderRadius: '10px', fontSize: '0.75rem', fontWeight: 800 }}>
                    {tab.count}
                  </span>
                )}
              </button>
            ))}
          {lastSyncTime && (
            <div style={{ marginLeft: 'auto', alignSelf: 'center', fontSize: '0.75rem', color: '#94a3b8' }}>
              Sincronizado: <b>{lastSyncTime}</b>
            </div>
          )}
        </div>

        {/* ── TAB 1: RESUMEN Y PEDIDOS FINCAS ──────────────────────────────── */}
        {activeTab === 'PEDIDOS' && (
          <div>
            {/* Filter Card */}
            <div style={{ background: '#fff', borderRadius: '12px', padding: '1.25rem', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', marginBottom: '1.5rem', border: '1px solid #f0f0f0' }}>
              <div style={{ fontSize: '0.88rem', fontWeight: 800, color: '#1c5236', textTransform: 'uppercase', marginBottom: '0.75rem', letterSpacing: '0.04em' }}>
                🔍 Filtros de Búsqueda (Cliente Master, Cliente Destino, PO#, Order#, Item, Producto, ShipDate, Delivery, Farm, AWB, Agencia)
              </div>
              <form onSubmit={handleSearchSubmit}>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(190px, 1fr))', gap: '0.75rem', marginBottom: '1rem' }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#1c5236', marginBottom: '0.2rem' }}>Cliente Master</label>
                    <select
                      value={filters.masterCustomer}
                      onChange={e => setFilters({ ...filters, masterCustomer: e.target.value })}
                      style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box', background: 'white', fontWeight: 600 }}
                    >
                      <option value="">— Todos los Master —</option>
                      {masterCustomerOptions.map(name => (
                        <option key={name} value={name}>{name}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#555', marginBottom: '0.2rem' }}>Cliente Destino (Ship / Sold To)</label>
                    <input
                      value={filters.shipToCustomer}
                      onChange={e => setFilters({ ...filters, shipToCustomer: e.target.value })}
                      placeholder="Buscar destinatario..."
                      style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }}
                    />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#555', marginBottom: '0.2rem' }}>PO#</label>
                    <input value={filters.po} onChange={e => setFilters({ ...filters, po: e.target.value })} placeholder="PO#..." style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#555', marginBottom: '0.2rem' }}>Order#</label>
                    <input value={filters.order} onChange={e => setFilters({ ...filters, order: e.target.value })} placeholder="Order#..." style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#555', marginBottom: '0.2rem' }}>Item (Código)</label>
                    <input value={filters.item} onChange={e => setFilters({ ...filters, item: e.target.value })} placeholder="Ej. 980076597" style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#555', marginBottom: '0.2rem' }}>Producto</label>
                    <input value={filters.prodDesc} onChange={e => setFilters({ ...filters, prodDesc: e.target.value })} placeholder="Nombre producto..." style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.2rem' }}>
                      <label style={{ fontSize: '0.75rem', fontWeight: 700, color: '#555' }}>Ship Date</label>
                      <select
                        value={filters.shipdateMode}
                        onChange={e => setFilters({ ...filters, shipdateMode: e.target.value })}
                        style={{ fontSize: '0.7rem', padding: '0.1rem 0.3rem', border: '1px solid #ccc', borderRadius: '4px', background: '#f9fafb', cursor: 'pointer' }}
                      >
                        <option value="single">Única</option>
                        <option value="range">Rango</option>
                      </select>
                    </div>
                    {filters.shipdateMode === 'single' ? (
                      <input type="date" value={filters.shipdate} onChange={e => setFilters({ ...filters, shipdate: e.target.value })} style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }} />
                    ) : (
                      <div style={{ display: 'flex', gap: '0.25rem' }}>
                        <input type="date" title="Desde" value={filters.shipdateFrom} onChange={e => setFilters({ ...filters, shipdateFrom: e.target.value })} style={{ width: '50%', padding: '0.35rem 0.3rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.73rem', boxSizing: 'border-box' }} />
                        <input type="date" title="Hasta" value={filters.shipdateTo} onChange={e => setFilters({ ...filters, shipdateTo: e.target.value })} style={{ width: '50%', padding: '0.35rem 0.3rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.73rem', boxSizing: 'border-box' }} />
                      </div>
                    )}
                  </div>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.2rem' }}>
                      <label style={{ fontSize: '0.75rem', fontWeight: 700, color: '#555' }}>Delivery Date</label>
                      <select
                        value={filters.deliverMode}
                        onChange={e => setFilters({ ...filters, deliverMode: e.target.value })}
                        style={{ fontSize: '0.7rem', padding: '0.1rem 0.3rem', border: '1px solid #ccc', borderRadius: '4px', background: '#f9fafb', cursor: 'pointer' }}
                      >
                        <option value="single">Única</option>
                        <option value="range">Rango</option>
                      </select>
                    </div>
                    {filters.deliverMode === 'single' ? (
                      <input type="date" value={filters.deliver} onChange={e => setFilters({ ...filters, deliver: e.target.value })} style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }} />
                    ) : (
                      <div style={{ display: 'flex', gap: '0.25rem' }}>
                        <input type="date" title="Desde" value={filters.deliverFrom} onChange={e => setFilters({ ...filters, deliverFrom: e.target.value })} style={{ width: '50%', padding: '0.35rem 0.3rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.73rem', boxSizing: 'border-box' }} />
                        <input type="date" title="Hasta" value={filters.deliverTo} onChange={e => setFilters({ ...filters, deliverTo: e.target.value })} style={{ width: '50%', padding: '0.35rem 0.3rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.73rem', boxSizing: 'border-box' }} />
                      </div>
                    )}
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#555', marginBottom: '0.2rem' }}>Finca</label>
                    <input value={filters.farm} onChange={e => setFilters({ ...filters, farm: e.target.value })} placeholder="Finca..." style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#555', marginBottom: '0.2rem' }}>AWB</label>
                    <input value={filters.awb} onChange={e => setFilters({ ...filters, awb: e.target.value })} placeholder="729-45452022..." style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }} />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#555', marginBottom: '0.2rem' }}>Agencia</label>
                    <input value={filters.agency} onChange={e => setFilters({ ...filters, agency: e.target.value })} placeholder="FEDEX, FLOWER..." style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #ddd', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }} />
                  </div>
                </div>
                <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
                  <button type="button" onClick={handleClearFilters} style={{ padding: '0.5rem 1.2rem', borderRadius: '6px', border: '1px solid #ddd', background: '#fff', cursor: 'pointer', fontSize: '0.85rem' }}>
                    Limpiar
                  </button>
                  <button type="submit" style={{ padding: '0.5rem 1.4rem', borderRadius: '6px', border: 'none', background: '#1c5236', color: '#fff', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem' }}>
                    🔍 Aplicar Filtros
                  </button>
                </div>
              </form>
            </div>

            {/* Section 1: RESUMEN POR DELIVERY DATE Y POR ITEM DE LAS ORDENES */}
            <div style={{ marginBottom: '2.5rem' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem', flexWrap: 'wrap', gap: '0.5rem' }}>
                <div>
                  <h2 style={{ margin: 0, fontSize: '1.2rem', fontWeight: 800, color: '#1a1a2e' }}>
                    1. RESUMEN POR DELIVERY DATE / Y POR ITEM DE LAS ÓRDENES
                  </h2>
                  <span style={{ fontSize: '0.8rem', color: '#666' }}>
                    INFORMACIÓN QUE ENTRA AL MOMENTO DE CARGAR LAS ÓRDENES (PROVIENE DEL MÓDULO DE ÓRDENES)
                  </span>
                </div>
                <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
                  <span style={{ background: '#dcfce7', color: '#166534', padding: '0.3rem 0.8rem', borderRadius: '12px', fontSize: '0.8rem', fontWeight: 700 }}>
                    Asignadas: {grandTotals.farmAssigned}
                  </span>
                  <span style={{ background: grandTotals.faltante > 0 ? '#fef3c7' : '#f3f4f6', color: grandTotals.faltante > 0 ? '#b45309' : '#374151', padding: '0.3rem 0.8rem', borderRadius: '12px', fontSize: '0.8rem', fontWeight: 700 }}>
                    Faltantes por Comprar: {grandTotals.faltante}
                  </span>
                  <button
                    type="button"
                    onClick={handleExportSummaryExcel}
                    style={{ background: '#16a34a', border: 'none', borderRadius: '8px', padding: '0.45rem 1rem', fontSize: '0.82rem', fontWeight: 800, color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.4rem', boxShadow: '0 2px 6px rgba(22,163,74,0.3)' }}
                    title="Exportar Resumen de Órdenes a Excel"
                  >
                    📥 Exportar a Excel
                  </button>
                </div>
              </div>

              {/* Summary Table */}
              <div style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 4px 14px rgba(0,0,0,0.06)', overflowX: 'auto', border: '1px solid #e5e7eb' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem', textAlign: 'left', minWidth: '1100px' }}>
                  <thead>
                    <tr style={{ background: '#1c5236', borderBottom: '2px solid #143d28', color: '#ffffff' }}>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff' }}>PO</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff' }}>ORDER</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff' }}>ITEM</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff' }}>ProdDesc</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff', textAlign: 'center' }}>Orddate</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff', textAlign: 'center' }}>SHIPDT</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff', textAlign: 'center' }}>Deliver</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff', textAlign: 'center' }}>QTY</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff', textAlign: 'center' }}>Farm Asigned</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff', textAlign: 'center' }}>Received</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff', textAlign: 'center' }}>Faltante</th>
                      <th style={{ padding: '0.75rem 0.8rem', fontWeight: 700, color: '#ffffff', textAlign: 'center' }}>Acción</th>
                    </tr>
                  </thead>
                  <tbody>
                    {loading ? (
                      <tr>
                        <td colSpan={12} style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>
                          Cargando resumen de órdenes...
                        </td>
                      </tr>
                    ) : groupedSummary.filter(g => g.totalFaltante > 0).length === 0 ? (
                      <tr>
                        <td colSpan={12} style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>
                          No hay órdenes pendientes o faltantes por asignar a fincas.
                        </td>
                      </tr>
                    ) : (
                      groupedSummary.filter(g => g.totalFaltante > 0).map(group => {
                        const isExpanded = expandedGroups.has(group.groupKey);
                        return (
                          <React.Fragment key={group.groupKey}>
                            {/* Individual breakdown rows if expanded */}
                            {isExpanded && group.lines.filter(l => l.faltante > 0).map(row => (
                              <tr key={row.id} style={{ borderBottom: '1px solid #f1f5f9', background: '#fff' }}>
                                <td style={{ padding: '0.55rem 0.8rem', fontWeight: 600, color: '#1c5236' }}>{row.po}</td>
                                <td style={{ padding: '0.55rem 0.8rem', color: '#4b5563' }}>{row.orderNumber}</td>
                                <td style={{ padding: '0.55rem 0.8rem', fontWeight: 700, color: '#dc2626', fontFamily: 'monospace' }}>{row.item}</td>
                                <td style={{ padding: '0.55rem 0.8rem', fontWeight: 600 }}>{row.prodDesc}</td>
                                <td style={{ padding: '0.55rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>
                                  {row.orddate || '—'}
                                </td>
                                <td style={{ padding: '0.55rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>
                                  {row.shipdt || '—'}
                                </td>
                                <td style={{ padding: '0.55rem 0.8rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 600 }}>
                                  {row.deliver || '—'}
                                </td>
                                <td style={{ padding: '0.55rem 0.8rem', textAlign: 'center', fontWeight: 700 }}>
                                  {row.qty}
                                </td>
                                <td style={{ padding: '0.55rem 0.8rem', textAlign: 'center', color: row.farmAssigned > 0 ? '#166534' : '#9ca3af', fontWeight: 600 }}>
                                  {row.farmAssigned}
                                </td>
                                <td style={{ padding: '0.55rem 0.8rem', textAlign: 'center', color: row.received > 0 ? '#1d4ed8' : '#9ca3af', fontWeight: 600 }}>
                                  {row.received}
                                </td>
                                <td style={{ padding: '0.55rem 0.8rem', textAlign: 'center', fontWeight: 700, color: row.faltante > 0 ? '#dc2626' : '#166534' }}>
                                  {row.faltante}
                                </td>
                                <td style={{ padding: '0.55rem 0.8rem', textAlign: 'center' }}>
                                  {row.status === 'FARM ASIGNED' ? (
                                    <button
                                      onClick={() => window.open(`/pedidos/print-labels/${row.id}`, '_blank')}
                                      style={{ padding: '0.25rem 0.55rem', borderRadius: '4px', border: 'none', background: '#2563eb', color: '#fff', cursor: 'pointer', fontSize: '0.72rem', fontWeight: 700 }}
                                    >
                                      🖨️ Etiqueta
                                    </button>
                                  ) : (
                                    <span style={{ fontSize: '0.72rem', color: '#9ca3af' }}>Pendiente</span>
                                  )}
                                </td>
                              </tr>
                            ))}

                            {/* Group Total Row (Blue Highlighted - "EL RESUMEN MUESTRA SOLO TOTALES") */}
                            <tr style={{ background: '#0284c7', color: '#fff', fontWeight: 700, borderBottom: '2px solid #0369a1' }}>
                              <td style={{ padding: '0.65rem 0.8rem' }} colSpan={2}>
                                <button
                                  onClick={() => toggleGroup(group.groupKey)}
                                  style={{ background: 'rgba(255,255,255,0.2)', border: 'none', color: '#fff', borderRadius: '4px', padding: '0.2rem 0.5rem', cursor: 'pointer', fontSize: '0.75rem', fontWeight: 700, marginRight: '0.5rem' }}
                                >
                                  {isExpanded ? '▲ Ocultar POs' : `▼ Ver ${group.lines.length} POs`}
                                </button>
                                <span>TOTAL {group.item}</span>
                              </td>
                              <td style={{ padding: '0.65rem 0.8rem', color: '#fee2e2', fontFamily: 'monospace', fontWeight: 900 }}>{group.item}</td>
                              <td style={{ padding: '0.65rem 0.8rem' }}>{group.prodDesc}</td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }} title="Fecha de orden más antigua del lote">
                                {group.lines.map(l => l.orddate).filter(Boolean).sort()[0] || '—'}
                              </td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>{group.shipdt || '—'}</td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>{group.deliver || '—'}</td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', fontSize: '0.95rem' }}>{group.totalQty}</td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', fontSize: '0.95rem' }}>{group.totalFarmAssigned}</td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', fontSize: '0.95rem' }}>{group.totalReceived}</td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', fontSize: '1rem', color: group.totalFaltante > 0 ? '#fef08a' : '#86efac' }}>
                                {group.totalFaltante}
                              </td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center' }}>
                                <button
                                  onClick={() => addItemToOrderForm(group)}
                                  style={{ padding: '0.3rem 0.75rem', borderRadius: '6px', border: 'none', background: '#22c55e', color: '#fff', cursor: 'pointer', fontWeight: 800, fontSize: '0.78rem', boxShadow: '0 2px 4px rgba(0,0,0,0.2)' }}
                                >
                                  + Comprar
                                </button>
                              </td>
                            </tr>
                          </React.Fragment>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>
            </div>

            {/* ── SECTION 2: FORMULARIO HACER PEDIDO A FINCAS (PLACE ORDER) ──── */}
            <div id="place-order-section" style={{ background: '#fff', borderRadius: '16px', padding: '1.75rem', boxShadow: '0 8px 24px rgba(0,0,0,0.08)', border: '2px solid #1c5236', marginBottom: '2.5rem' }}>
              <div style={{ borderBottom: '2px solid #e5e7eb', paddingBottom: '1rem', marginBottom: '1.25rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '1rem' }}>
                <div>
                  <h2 style={{ margin: 0, fontSize: '1.35rem', fontWeight: 900, color: '#1c5236' }}>
                    🛒 FORMULARIO DE COMPRA A FINCAS (PLACE ORDER)
                  </h2>
                  <p style={{ margin: '0.2rem 0 0', color: '#666', fontSize: '0.85rem' }}>
                    Asignación con prioridad FIFO por fecha de orden más antigua. Genera códigos únicos, etiquetas PDF y Excel para la finca.
                  </p>
                </div>
                <button
                  type="button"
                  onClick={addBlankOrderLine}
                  style={{ padding: '0.5rem 1.1rem', borderRadius: '8px', border: '1px solid #1c5236', background: '#f0fdf4', color: '#1c5236', fontWeight: 700, cursor: 'pointer', fontSize: '0.85rem' }}
                >
                  + Añadir Línea Manual
                </button>
              </div>

              {/* Master Selectors */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '1.25rem', marginBottom: '1.5rem', background: '#f8fafc', padding: '1.25rem', borderRadius: '10px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 800, color: '#1e293b', marginBottom: '0.35rem' }}>
                    1. ESCOGER FINCA *
                  </label>
                  <select
                    value={selectedFarmId}
                    onChange={e => setSelectedFarmId(e.target.value)}
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '2px solid #cbd5e1', borderRadius: '8px', fontSize: '0.9rem', fontWeight: 600, background: '#fff' }}
                  >
                    <option value="">— Seleccionar Finca Proveedora —</option>
                    {farms.map(f => (
                      <option key={f.id} value={f.id}>
                        {f.name} {f.ruc ? `(RUC: ${f.ruc})` : ''} {f.country ? `[${f.country}]` : ''}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 800, color: '#1e293b', marginBottom: '0.35rem' }}>
                    2. ESCOGER AGENCIA DE CARGA *
                  </label>
                  <select
                    value={selectedAgency}
                    onChange={e => {
                      const newAg = e.target.value;
                      setSelectedAgency(newAg);
                      const currentG = activeGuias.find(x => x.awb === selectedAwb);
                      if (currentG && currentG.agency.toUpperCase() !== newAg.toUpperCase()) {
                        setSelectedAwb('');
                      }
                    }}
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '2px solid #cbd5e1', borderRadius: '8px', fontSize: '0.9rem', fontWeight: 600, background: '#fff' }}
                  >
                    {activeAgencies.length === 0 ? (
                      <option value="">— No hay agencias con guías activas —</option>
                    ) : (
                      activeAgencies.map(ag => (
                        <option key={ag} value={ag}>{ag}</option>
                      ))
                    )}
                  </select>
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 800, color: '#1e293b', marginBottom: '0.35rem' }}>
                    3. ESCOGER AWB (GUÍA AÉREA) *
                  </label>
                  <select
                    value={selectedAwb}
                    onChange={e => {
                      const val = e.target.value;
                      setSelectedAwb(val);
                      const g = activeGuias.find(x => x.awb === val);
                      if (g && g.agency) {
                        setSelectedAgency(g.agency);
                      }
                    }}
                    style={{ width: '100%', padding: '0.6rem 0.8rem', border: '2px solid #cbd5e1', borderRadius: '8px', fontSize: '0.88rem', fontWeight: 700, fontFamily: 'monospace', background: '#fff' }}
                  >
                    <option value="">— Seleccionar Guía Aérea Activa —</option>
                    {activeGuias
                      .filter(g => !selectedAgency || g.agency.toUpperCase() === selectedAgency.toUpperCase())
                      .map(g => {
                        const digits = g.awb.replace(/\D/g, '');
                        const formatted = digits.length === 11 ? `${digits.slice(0, 3)}-${digits.slice(3, 7)}-${digits.slice(7)}` : g.awb;
                        const ship = formatDateToYYYYMMDD(g.shipDate) || (g.deliverDate ? calculateShipDate(formatDateToYYYYMMDD(g.deliverDate), g.agency) : '');
                        return (
                          <option key={g.id} value={g.awb}>
                            {formatted} - {g.agency} - SHIPDATE {ship}
                          </option>
                        );
                      })}
                  </select>
                  {selectedAwb && (
                    <div style={{ marginTop: '0.35rem', fontSize: '0.76rem', fontWeight: 800, color: '#15803d', fontFamily: 'monospace', background: '#dcfce7', padding: '0.3rem 0.6rem', borderRadius: '6px', border: '1px solid #86efac' }}>
                      ✓ {getFormattedAwbDisplay(selectedAwb, selectedAgency)}
                    </div>
                  )}
                </div>
              </div>

              {/* Order Lines Table */}
              {orderLinesForm.length === 0 ? (
                <div style={{ padding: '2.5rem', textAlign: 'center', background: '#f8fafc', borderRadius: '10px', color: '#64748b', border: '2px dashed #cbd5e1' }}>
                  <p style={{ margin: '0 0 0.5rem', fontSize: '1rem', fontWeight: 600 }}>No hay ítems agregados a la orden de compra.</p>
                  <p style={{ margin: 0, fontSize: '0.85rem' }}>Haz clic en <strong>"+ Comprar"</strong> en la tabla de arriba o presiona <strong>"+ Añadir Línea Manual"</strong>.</p>
                </div>
              ) : (
                <div style={{ overflowX: 'auto', marginBottom: '1.5rem' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem', textAlign: 'left', minWidth: '1200px' }}>
                    <thead>
                      <tr style={{ background: '#1c5236', color: '#fff' }}>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700 }}>ITEM</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700 }}>ProdDesc</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'center' }}>Faltante</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'center', background: '#15803d' }}>Cajas a Comprar *</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'center' }}>Box Type</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'right' }}>Precio Caja ($)</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'right' }}>Precio Total ($)</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'center' }}>SALIDA FINCA</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'center' }}>SHIPDATE</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'center' }}>DELIVER</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'center' }}>AGENCIA</th>
                        <th style={{ padding: '0.75rem 0.6rem', fontWeight: 700, textAlign: 'center' }}>AWB</th>
                        <th style={{ padding: '0.75rem 0.6rem', textAlign: 'center' }}>✕</th>
                      </tr>
                    </thead>
                    <tbody>
                      {orderLinesForm.map((line, idx) => {
                        const lineTotal = line.farmQty * line.unitPrice;
                        return (
                          <tr key={idx} style={{ borderBottom: '1px solid #e2e8f0', background: idx % 2 === 0 ? '#fff' : '#f8fafc' }}>
                            <td style={{ padding: '0.5rem 0.6rem', width: '130px' }}>
                              <select
                                value={line.itemCode}
                                onChange={e => updateOrderLineField(idx, 'itemCode', e.target.value)}
                                style={{ width: '100%', padding: '0.4rem', border: '1px solid #cbd5e1', borderRadius: '4px', fontSize: '0.8rem', fontWeight: 700, fontFamily: 'monospace' }}
                              >
                                <option value="">— Código —</option>
                                {products.map(p => (
                                  <option key={p.id} value={p.code}>{p.code} - {p.name}</option>
                                ))}
                              </select>
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', minWidth: '180px', fontWeight: 600 }}>
                              {line.prodDesc || '—'}
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'center', fontWeight: 800, color: '#dc2626', fontSize: '0.9rem' }} title="Cajas faltantes por comprar">
                              {line.orderQty}
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'center', width: '90px' }}>
                              <input
                                type="number"
                                min="1"
                                value={line.farmQty}
                                onChange={e => updateOrderLineField(idx, 'farmQty', parseInt(e.target.value, 10) || 1)}
                                style={{ width: '100%', padding: '0.4rem', border: '2px solid #22c55e', borderRadius: '4px', fontSize: '0.9rem', textAlign: 'center', fontWeight: 800 }}
                              />
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'center', minWidth: '120px' }}>
                              <select
                                value={line.boxType}
                                onChange={e => updateOrderLineField(idx, 'boxType', e.target.value)}
                                style={{ width: '100%', padding: '0.4rem', border: '1px solid #cbd5e1', borderRadius: '4px', fontSize: '0.78rem', fontWeight: 600 }}
                              >
                                {(() => {
                                  const opts = getFilteredBoxTypesForFarm(selectedFarmId, line.boxType);
                                  const usfOpts = opts.filter(o => o.group.includes('USF'));
                                  const farmOpts = opts.filter(o => o.group.includes('Finca'));
                                  const otherOpts = opts.filter(o => o.group === 'Otras');
                                  return (
                                    <>
                                      <optgroup label="📦 Cajas USF Estándar (3)">
                                        {usfOpts.map(o => (
                                          <option key={o.code} value={o.code}>{o.label}</option>
                                        ))}
                                      </optgroup>
                                      {farmOpts.length > 0 && (
                                        <optgroup label="🌻 Cajas de Finca (máx 3)">
                                          {farmOpts.map(o => (
                                            <option key={o.code} value={o.code}>{o.label}</option>
                                          ))}
                                        </optgroup>
                                      )}
                                      {otherOpts.length > 0 && (
                                        <optgroup label="Otras">
                                          {otherOpts.map(o => (
                                            <option key={o.code} value={o.code}>{o.label}</option>
                                          ))}
                                        </optgroup>
                                      )}
                                    </>
                                  );
                                })()}
                              </select>
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'right', width: '100px' }}>
                              <input
                                type="number"
                                step="0.5"
                                min="0"
                                value={line.unitPrice}
                                onChange={e => updateOrderLineField(idx, 'unitPrice', parseFloat(e.target.value) || 0)}
                                style={{ width: '100%', padding: '0.4rem', border: '1px solid #cbd5e1', borderRadius: '4px', fontSize: '0.85rem', textAlign: 'right', fontWeight: 600 }}
                              />
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'right', fontWeight: 800, color: '#1c5236', fontSize: '0.9rem' }}>
                              ${lineTotal.toFixed(2)}
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'center', width: '130px' }}>
                              <input
                                type="date"
                                value={line.farmDepartureDate}
                                onChange={e => updateOrderLineField(idx, 'farmDepartureDate', e.target.value)}
                                style={{ width: '100%', padding: '0.35rem', border: '1px solid #cbd5e1', borderRadius: '4px', fontSize: '0.78rem' }}
                              />
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'center', width: '130px' }}>
                              <input
                                type="date"
                                value={line.shipDate}
                                onChange={e => updateOrderLineField(idx, 'shipDate', e.target.value)}
                                style={{ width: '100%', padding: '0.35rem', border: '1px solid #cbd5e1', borderRadius: '4px', fontSize: '0.78rem' }}
                              />
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'center', width: '130px' }}>
                              <input
                                type="date"
                                value={line.deliverDate}
                                onChange={e => updateOrderLineField(idx, 'deliverDate', e.target.value)}
                                style={{ width: '100%', padding: '0.35rem', border: '1px solid #cbd5e1', borderRadius: '4px', fontSize: '0.78rem' }}
                              />
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'center', fontWeight: 600, color: '#475569' }}>
                              {selectedAgency}
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 800, color: selectedAwb ? '#15803d' : '#64748b', fontSize: '0.78rem', whiteSpace: 'nowrap' }}>
                              {selectedAwb ? getFormattedAwbDisplay(selectedAwb, selectedAgency) : '—'}
                            </td>
                            <td style={{ padding: '0.5rem 0.6rem', textAlign: 'center' }}>
                              <button
                                type="button"
                                onClick={() => removeOrderLine(idx)}
                                style={{ background: '#fee2e2', border: 'none', color: '#dc2626', borderRadius: '4px', padding: '0.3rem 0.6rem', cursor: 'pointer', fontWeight: 800 }}
                              >
                                ✕
                              </button>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}

              {/* Notice Banner & Submit Button */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '1rem', borderTop: '2px solid #f1f5f9', paddingTop: '1.25rem' }}>
                <div style={{ background: '#fef3c7', borderLeft: '4px solid #f59e0b', padding: '0.75rem 1rem', borderRadius: '4px', maxWidth: '650px', fontSize: '0.82rem', color: '#92400e' }}>
                  <strong>📌 Reglas Obligatorias:</strong>
                  <br />• La orden da prioridad <strong>FIFO a las órdenes con Order Date más antiguo</strong>.
                  <br />• Se generarán los códigos únicos (BOX#) y etiquetas PDF para cada caja.
                  <br />• <em>"La orden debe ser confirmada en Línea y las etiquetas deben venir pegadas en las cajas, en UN SOLO LADO de la misma."</em>
                </div>

                <div style={{ display: 'flex', gap: '1rem', alignItems: 'center' }}>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: '0.8rem', color: '#64748b' }}>Total Cajas: <strong>{orderLinesForm.reduce((acc, l) => acc + l.farmQty, 0)}</strong></div>
                    <div style={{ fontSize: '1.25rem', fontWeight: 900, color: '#1c5236' }}>
                      ${orderLinesForm.reduce((acc, l) => acc + l.farmQty * l.unitPrice, 0).toFixed(2)}
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={handlePlaceOrder}
                    disabled={placingOrder || orderLinesForm.length === 0}
                    style={{
                      padding: '0.9rem 2.5rem',
                      borderRadius: '12px',
                      border: 'none',
                      background: 'linear-gradient(135deg, #16a34a, #15803d)',
                      color: '#fff',
                      cursor: placingOrder ? 'not-allowed' : 'pointer',
                      fontWeight: 900,
                      fontSize: '1.1rem',
                      letterSpacing: '0.04em',
                      boxShadow: '0 6px 18px rgba(22,163,74,0.35)',
                      transition: 'all 0.2s ease'
                    }}
                  >
                    {placingOrder ? '⏳ Procesando...' : '🚀 PLACE ORDER'}
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ── TAB 2: ASIGNACIÓN DE GUÍAS (PASO 2) ───────────────────────────── */}
        {activeTab === 'GUIAS' && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', flexWrap: 'wrap', gap: '1rem' }}>
              <div>
                <h2 style={{ margin: 0, fontSize: '1.4rem', fontWeight: 800, color: '#1c5236' }}>
                  ✈️ Módulo de Asignación de Guías Aéreas
                </h2>
                <p style={{ margin: '0.2rem 0 0', color: '#666', fontSize: '0.85rem' }}>
                  Registro y renovación semanal de guías de carga por agencia, fecha de entrega y vuelo. Al archivar una guía, queda protegida y no afecta órdenes pasadas.
                </p>
              </div>
              <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
                {/* View Mode Pills */}
                <div style={{ display: 'flex', background: '#f1f5f9', padding: '0.25rem', borderRadius: '8px' }}>
                  <button
                    type="button"
                    onClick={() => { setGuiaViewMode('ACTIVE'); setSelectedGuiaIds(new Set()); }}
                    style={{
                      padding: '0.4rem 0.85rem',
                      borderRadius: '6px',
                      border: 'none',
                      background: guiaViewMode === 'ACTIVE' ? '#1c5236' : 'transparent',
                      color: guiaViewMode === 'ACTIVE' ? '#fff' : '#475569',
                      fontWeight: 700,
                      fontSize: '0.82rem',
                      cursor: 'pointer'
                    }}
                  >
                    ✈️ Activas ({activeGuias.length})
                  </button>
                  <button
                    type="button"
                    onClick={() => { setGuiaViewMode('ARCHIVED'); setSelectedGuiaIds(new Set()); }}
                    style={{
                      padding: '0.4rem 0.85rem',
                      borderRadius: '6px',
                      border: 'none',
                      background: guiaViewMode === 'ARCHIVED' ? '#1c5236' : 'transparent',
                      color: guiaViewMode === 'ARCHIVED' ? '#fff' : '#475569',
                      fontWeight: 700,
                      fontSize: '0.82rem',
                      cursor: 'pointer'
                    }}
                  >
                    📁 Archivadas ({archivedGuias.length})
                  </button>
                  <button
                    type="button"
                    onClick={() => { setGuiaViewMode('ALL'); setSelectedGuiaIds(new Set()); }}
                    style={{
                      padding: '0.4rem 0.85rem',
                      borderRadius: '6px',
                      border: 'none',
                      background: guiaViewMode === 'ALL' ? '#1c5236' : 'transparent',
                      color: guiaViewMode === 'ALL' ? '#fff' : '#475569',
                      fontWeight: 700,
                      fontSize: '0.82rem',
                      cursor: 'pointer'
                    }}
                  >
                    Todas ({guias.length})
                  </button>
                </div>

                <button
                  type="button"
                  onClick={handleExportGuiasExcel}
                  style={{ padding: '0.6rem 1.2rem', borderRadius: '8px', border: 'none', background: '#16a34a', color: '#fff', cursor: 'pointer', fontWeight: 800, fontSize: '0.85rem', display: 'flex', alignItems: 'center', gap: '0.4rem', boxShadow: '0 2px 6px rgba(22,163,74,0.3)' }}
                  title="Exportar listado de guías a Excel"
                >
                  📥 Exportar a Excel
                </button>

                <button
                  onClick={openNewGuiaModal}
                  style={{ padding: '0.6rem 1.4rem', borderRadius: '8px', border: 'none', background: '#1c5236', color: '#fff', cursor: 'pointer', fontWeight: 800, fontSize: '0.88rem', display: 'flex', alignItems: 'center', gap: '0.4rem', boxShadow: '0 2px 6px rgba(28,82,54,0.3)' }}
                >
                  + Nueva Guía AWB
                </button>
              </div>
            </div>

            {/* Bulk Actions Bar for Guías */}
            {selectedGuiaIds.size > 0 && (
              <div style={{ background: '#f8fafc', border: '1px solid #cbd5e1', padding: '0.75rem 1.25rem', borderRadius: '10px', marginBottom: '1rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '0.75rem' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                  <span style={{ fontWeight: 800, color: '#1e293b', fontSize: '0.88rem' }}>
                    ✓ {selectedGuiaIds.size} {selectedGuiaIds.size === 1 ? 'guía seleccionada' : 'guías seleccionadas'}
                  </span>
                  <button
                    type="button"
                    onClick={() => setSelectedGuiaIds(new Set())}
                    style={{ background: '#fff', border: '1px solid #cbd5e1', borderRadius: '6px', padding: '0.3rem 0.6rem', fontSize: '0.75rem', fontWeight: 600, color: '#64748b', cursor: 'pointer' }}
                  >
                    Deseleccionar
                  </button>
                </div>
                <div style={{ display: 'flex', gap: '0.6rem' }}>
                  {guiaViewMode !== 'ARCHIVED' && (
                    <button
                      type="button"
                      onClick={() => handleBulkArchiveGuias(true)}
                      style={{ background: '#fef3c7', border: '1px solid #f59e0b', borderRadius: '6px', padding: '0.4rem 0.9rem', fontSize: '0.82rem', fontWeight: 800, color: '#92400e', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.4rem' }}
                      title="Archivar guías seleccionadas para renovar semana"
                    >
                      📁 Archivar Seleccionadas ({selectedGuiaIds.size})
                    </button>
                  )}
                  {guiaViewMode !== 'ACTIVE' && (
                    <button
                      type="button"
                      onClick={() => handleBulkArchiveGuias(false)}
                      style={{ background: '#dcfce7', border: '1px solid #16a34a', borderRadius: '6px', padding: '0.4rem 0.9rem', fontSize: '0.82rem', fontWeight: 800, color: '#166534', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.4rem' }}
                      title="Reactivar guías seleccionadas para nuevos pedidos"
                    >
                      📂 Desarchivar Seleccionadas ({selectedGuiaIds.size})
                    </button>
                  )}
                </div>
              </div>
            )}

            <div style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 4px 12px rgba(0,0,0,0.06)', overflow: 'hidden', border: '1px solid #e5e7eb' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.88rem', textAlign: 'left' }}>
                <thead>
                  <tr style={{ background: '#1c5236', color: '#fff' }}>
                    <th style={{ padding: '0.85rem 0.75rem', textAlign: 'center', width: '40px' }}>
                      <input
                        type="checkbox"
                        checked={displayedGuias.length > 0 && selectedGuiaIds.size === displayedGuias.length}
                        onChange={toggleSelectAllGuias}
                        style={{ cursor: 'pointer', width: '16px', height: '16px' }}
                        title="Seleccionar todas"
                      />
                    </th>
                    <th style={{ padding: '0.85rem 1rem', fontWeight: 700 }}>AGENCIA</th>
                    <th style={{ padding: '0.85rem 1rem', fontWeight: 700, textAlign: 'center' }}>DELIVER</th>
                    <th style={{ padding: '0.85rem 1rem', fontWeight: 700, textAlign: 'center' }}>SHIPDATE</th>
                    <th style={{ padding: '0.85rem 1rem', fontWeight: 700 }}>AWB</th>
                    <th style={{ padding: '0.85rem 1rem', fontWeight: 700, textAlign: 'center' }}>MASTER</th>
                    <th style={{ padding: '0.85rem 1rem', fontWeight: 700, textAlign: 'center' }}>ESTADO</th>
                    <th style={{ padding: '0.85rem 1rem', fontWeight: 700, textAlign: 'center' }}>ACCIONES</th>
                  </tr>
                </thead>
                <tbody>
                  {displayedGuias.length === 0 ? (
                    <tr>
                      <td colSpan={8} style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>
                        {guiaViewMode === 'ARCHIVED'
                          ? 'No hay guías aéreas archivadas.'
                          : guiaViewMode === 'ACTIVE'
                          ? 'No hay guías aéreas activas. Haz clic en "+ Nueva Guía AWB".'
                          : 'No hay guías aéreas registradas.'}
                      </td>
                    </tr>
                  ) : (
                    displayedGuias.map((g, i) => {
                      const isArchived = g.status === 'ARCHIVED';
                      const isSelected = selectedGuiaIds.has(g.id);
                      return (
                        <tr key={g.id} style={{ borderBottom: '1px solid #eee', background: isSelected ? '#f0fdf4' : (i % 2 === 0 ? '#fff' : '#f9fafb') }}>
                          <td style={{ padding: '0.8rem 0.75rem', textAlign: 'center' }}>
                            <input
                              type="checkbox"
                              checked={isSelected}
                              onChange={() => toggleSelectGuia(g.id)}
                              style={{ cursor: 'pointer', width: '16px', height: '16px' }}
                            />
                          </td>
                          <td style={{ padding: '0.8rem 1rem', fontWeight: 800, color: isArchived ? '#64748b' : '#1e293b' }}>
                            {g.agency}
                          </td>
                          <td style={{ padding: '0.8rem 1rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 600, color: isArchived ? '#64748b' : 'inherit' }}>
                            {formatDateToYYYYMMDD(g.deliverDate)}
                          </td>
                          <td style={{ padding: '0.8rem 1rem', textAlign: 'center', fontFamily: 'monospace', color: isArchived ? '#64748b' : 'inherit' }}>
                            {formatDateToYYYYMMDD(g.shipDate)}
                          </td>
                          <td style={{ padding: '0.8rem 1rem', fontFamily: 'monospace', fontWeight: 800, color: isArchived ? '#64748b' : '#1c5236', fontSize: '1rem' }}>
                            {g.awb}
                          </td>
                          <td style={{ padding: '0.8rem 1rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 800, color: isArchived ? '#64748b' : '#2563eb' }}>
                            {g.master}
                            <span style={{ fontSize: '0.7rem', color: '#64748b', display: 'block' }}>(Últimos 4 dígitos)</span>
                          </td>
                          <td style={{ padding: '0.8rem 1rem', textAlign: 'center' }}>
                            {isArchived ? (
                              <span style={{ background: '#f1f5f9', color: '#475569', padding: '0.2rem 0.6rem', borderRadius: '10px', fontSize: '0.75rem', fontWeight: 800, border: '1px solid #cbd5e1' }}>
                                📁 ARCHIVADA
                              </span>
                            ) : (
                              <span style={{ background: '#dcfce7', color: '#166534', padding: '0.2rem 0.6rem', borderRadius: '10px', fontSize: '0.75rem', fontWeight: 800 }}>
                                ACTIVE
                              </span>
                            )}
                          </td>
                          <td style={{ padding: '0.8rem 1rem', textAlign: 'center' }}>
                            <div style={{ display: 'flex', gap: '0.35rem', justifyContent: 'center', flexWrap: 'wrap' }}>
                              {!isArchived ? (
                                <>
                                  <button
                                    type="button"
                                    onClick={() => {
                                      setSelectedAwb(g.awb);
                                      setSelectedAgency(g.agency);
                                      setActiveTab('PEDIDOS');
                                    }}
                                    style={{ background: '#f0fdf4', border: '1px solid #1c5236', borderRadius: '6px', padding: '0.35rem 0.65rem', color: '#1c5236', fontWeight: 700, fontSize: '0.78rem', cursor: 'pointer' }}
                                    title="Usar en Pedido"
                                  >
                                    Usar en Pedido
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => setSelectedAwbForReport({ awb: g.awb, agency: g.agency })}
                                    style={{ background: '#f5f3ff', border: '1px solid #8b5cf6', borderRadius: '6px', padding: '0.35rem 0.65rem', color: '#6d28d9', fontWeight: 800, fontSize: '0.78rem', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.25rem' }}
                                    title="Ver Reporte Guía AWB Master (Excel/PDF)"
                                  >
                                    📋 Reporte Master
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => handleArchiveGuia(g.id, true)}
                                    style={{ background: '#fef3c7', border: '1px solid #f59e0b', borderRadius: '6px', padding: '0.35rem 0.65rem', color: '#92400e', fontWeight: 800, fontSize: '0.78rem', cursor: 'pointer' }}
                                    title="Archivar esta guía (para renovar semana y proteger órdenes pasadas)"
                                  >
                                    📁 Archivar
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => openEditGuiaModal(g)}
                                    style={{ background: '#eff6ff', border: '1px solid #3b82f6', borderRadius: '6px', padding: '0.35rem 0.65rem', color: '#1d4ed8', fontWeight: 700, fontSize: '0.78rem', cursor: 'pointer' }}
                                    title="Editar Guía AWB"
                                  >
                                    ✏️ Editar
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => handleDeleteGuia(g.id)}
                                    style={{ background: '#fee2e2', border: 'none', borderRadius: '6px', padding: '0.35rem 0.6rem', color: '#dc2626', cursor: 'pointer', fontSize: '0.78rem' }}
                                    title="Eliminar Guía"
                                  >
                                    🗑️
                                  </button>
                                </>
                              ) : (
                                <>
                                  <button
                                    type="button"
                                    onClick={() => setSelectedAwbForReport({ awb: g.awb, agency: g.agency })}
                                    style={{ background: '#f5f3ff', border: '1px solid #8b5cf6', borderRadius: '6px', padding: '0.35rem 0.65rem', color: '#6d28d9', fontWeight: 800, fontSize: '0.78rem', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.25rem' }}
                                    title="Ver Reporte Guía AWB Master (Excel/PDF)"
                                  >
                                    📋 Reporte Master
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => handleArchiveGuia(g.id, false)}
                                    style={{ background: '#dcfce7', border: '1px solid #16a34a', borderRadius: '6px', padding: '0.35rem 0.75rem', color: '#166534', fontWeight: 800, fontSize: '0.78rem', cursor: 'pointer' }}
                                    title="Desarchivar y reactivar guía para nuevos pedidos"
                                  >
                                    📂 Desarchivar
                                  </button>
                                  <button
                                    type="button"
                                    disabled
                                    style={{ background: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: '6px', padding: '0.35rem 0.55rem', color: '#94a3b8', fontSize: '0.78rem', cursor: 'not-allowed' }}
                                    title="Guía archivada: bloqueada para proteger órdenes pasadas"
                                  >
                                    🔒 Editar
                                  </button>
                                  <button
                                    type="button"
                                    disabled
                                    style={{ background: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: '6px', padding: '0.35rem 0.55rem', color: '#94a3b8', fontSize: '0.78rem', cursor: 'not-allowed' }}
                                    title="Guía archivada: no se puede eliminar para proteger órdenes pasadas"
                                  >
                                    🔒 Eliminar
                                  </button>
                                </>
                              )}
                            </div>
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* ── TAB 3: HISTORIAL DE COMPRAS A FINCAS ─────────────────────────── */}
        {activeTab === 'HISTORIAL' && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', flexWrap: 'wrap', gap: '1rem' }}>
              <div>
                <h2 style={{ margin: 0, fontSize: '1.4rem', fontWeight: 800, color: '#1c5236' }}>
                  📋 Historial de Cajas Compradas a Fincas
                </h2>
                <p style={{ margin: '0.2rem 0 0', color: '#64748b', fontSize: '0.85rem' }}>
                  Detalle y consolidado de compras a fincas con filtros de búsqueda, edición simultánea, cantidades y control de cancelaciones.
                </p>
              </div>
              <div style={{ display: 'flex', gap: '0.5rem', background: '#f1f5f9', padding: '0.25rem', borderRadius: '8px' }}>
                <button
                  type="button"
                  onClick={() => setHistorialViewMode('GROUPED')}
                  style={{
                    padding: '0.45rem 0.9rem',
                    borderRadius: '6px',
                    border: 'none',
                    background: historialViewMode === 'GROUPED' ? '#1c5236' : 'transparent',
                    color: historialViewMode === 'GROUPED' ? '#fff' : '#475569',
                    fontWeight: 700,
                    fontSize: '0.82rem',
                    cursor: 'pointer'
                  }}
                >
                  📊 Vista Agrupada por Totales ({historialGroups.length})
                </button>
                <button
                  type="button"
                  onClick={() => setHistorialViewMode('INDIVIDUAL')}
                  style={{
                    padding: '0.45rem 0.9rem',
                    borderRadius: '6px',
                    border: 'none',
                    background: historialViewMode === 'INDIVIDUAL' ? '#1c5236' : 'transparent',
                    color: historialViewMode === 'INDIVIDUAL' ? '#fff' : '#475569',
                    fontWeight: 700,
                    fontSize: '0.82rem',
                    cursor: 'pointer'
                  }}
                >
                  📦 Vista Cajas Individuales ({filteredPurchasedLines.length})
                </button>
              </div>
            </div>

            {/* ── FILTROS DE BÚSQUEDA HISTORIAL ────────────────────────────── */}
            <div style={{ background: '#fff', borderRadius: '12px', padding: '1rem 1.25rem', boxShadow: '0 2px 8px rgba(0,0,0,0.05)', marginBottom: '1.25rem', border: '1px solid #e2e8f0' }}>
              <form onSubmit={handleApplyHistorialFilters}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem', flexWrap: 'wrap', gap: '0.5rem' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                    <span style={{ fontSize: '0.85rem', fontWeight: 800, color: '#1c5236', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                      🔍 Filtros de Búsqueda de Compras
                    </span>
                    {activeHistorialFilterCount > 0 && (
                      <span style={{ background: '#dcfce7', color: '#166534', padding: '0.15rem 0.55rem', borderRadius: '10px', fontSize: '0.72rem', fontWeight: 700 }}>
                        {activeHistorialFilterCount} {activeHistorialFilterCount === 1 ? 'filtro activo' : 'filtros activos'}
                      </span>
                    )}
                  </div>
                  <div style={{ display: 'flex', gap: '0.6rem', alignItems: 'center' }}>
                    <span style={{ fontSize: '0.78rem', color: '#64748b' }}>
                      Mostrando {historialViewMode === 'GROUPED' ? `${historialGroups.length} grupos (${filteredPurchasedLines.length} cajas)` : `${filteredPurchasedLines.length} cajas`}
                    </span>
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: '0.65rem' }}>
                  {/* 1. Cliente (Sólo admin) */}
                  {!isFarmUser && (
                    <div>
                      <label style={{ display: 'block', fontSize: '0.72rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Cliente / PO</label>
                      <input
                        placeholder="Ej. New York..."
                        value={historialFilters.customer}
                        onChange={e => setHistorialFilters({ ...historialFilters, customer: e.target.value })}
                        list="historial-customers-datalist"
                        style={{ width: '100%', padding: '0.42rem 0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.78rem', boxSizing: 'border-box' }}
                      />
                      <datalist id="historial-customers-datalist">
                        {masterCustomerOptions.map(c => <option key={c} value={c} />)}
                      </datalist>
                    </div>
                  )}
                  {/* 2. Finca (Sólo admin) */}
                  {!isFarmUser && (
                    <div>
                      <label style={{ display: 'block', fontSize: '0.72rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Finca</label>
                      <select
                        value={historialFilters.farmId}
                        onChange={e => setHistorialFilters({ ...historialFilters, farmId: e.target.value })}
                        style={{ width: '100%', padding: '0.42rem 0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.78rem', boxSizing: 'border-box' }}
                      >
                        <option value="">Todas las fincas</option>
                        {farms.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
                      </select>
                    </div>
                  )}
                  {/* 3. Item */}
                  <div>
                    <label style={{ display: 'block', fontSize: '0.72rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Ítem</label>
                    <input
                      placeholder="Código ítem..."
                      value={historialFilters.item}
                      onChange={e => setHistorialFilters({ ...historialFilters, item: e.target.value })}
                      list="historial-items-datalist"
                      style={{ width: '100%', padding: '0.42rem 0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.78rem', boxSizing: 'border-box' }}
                    />
                    <datalist id="historial-items-datalist">
                      {products.map(p => <option key={p.id} value={p.code}>{p.name}</option>)}
                    </datalist>
                  </div>
                  {/* 4. Producto */}
                  <div>
                    <label style={{ display: 'block', fontSize: '0.72rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Producto</label>
                    <input
                      placeholder="Nombre flor..."
                      value={historialFilters.prodDesc}
                      onChange={e => setHistorialFilters({ ...historialFilters, prodDesc: e.target.value })}
                      list="historial-products-datalist"
                      style={{ width: '100%', padding: '0.42rem 0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.78rem', boxSizing: 'border-box' }}
                    />
                    <datalist id="historial-products-datalist">
                      {products.map(p => <option key={p.id} value={p.name}>{p.code}</option>)}
                    </datalist>
                  </div>
                  {/* 5. Precio */}
                  <div>
                    <label style={{ display: 'block', fontSize: '0.72rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Precio Unit ($)</label>
                    <input
                      placeholder="Ej. 40.00"
                      value={historialFilters.price}
                      onChange={e => setHistorialFilters({ ...historialFilters, price: e.target.value })}
                      style={{ width: '100%', padding: '0.42rem 0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.78rem', boxSizing: 'border-box' }}
                    />
                  </div>
                  {/* 6. Fecha Salida Finca */}
                  <div>
                    <label style={{ display: 'block', fontSize: '0.72rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Salida Finca</label>
                    <input
                      type="date"
                      value={historialFilters.departureDate}
                      onChange={e => setHistorialFilters({ ...historialFilters, departureDate: e.target.value })}
                      style={{ width: '100%', padding: '0.42rem 0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.78rem', boxSizing: 'border-box' }}
                    />
                  </div>
                  {/* 7. Fecha Delivery (Sólo admin) */}
                  {!isFarmUser && (
                    <div>
                      <label style={{ display: 'block', fontSize: '0.72rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Delivery</label>
                      <input
                        type="date"
                        value={historialFilters.deliverDate}
                        onChange={e => setHistorialFilters({ ...historialFilters, deliverDate: e.target.value })}
                        style={{ width: '100%', padding: '0.42rem 0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.78rem', boxSizing: 'border-box' }}
                      />
                    </div>
                  )}
                  {/* 8. Agencia */}
                  <div>
                    <label style={{ display: 'block', fontSize: '0.72rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Agencia Carga</label>
                    <input
                      placeholder="Ej. FEDEX..."
                      value={historialFilters.agency}
                      onChange={e => setHistorialFilters({ ...historialFilters, agency: e.target.value })}
                      style={{ width: '100%', padding: '0.42rem 0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.78rem', boxSizing: 'border-box' }}
                    />
                  </div>
                  {/* 9. Guía Aérea */}
                  <div>
                    <label style={{ display: 'block', fontSize: '0.72rem', fontWeight: 700, color: '#475569', marginBottom: '0.2rem' }}>Guía AWB</label>
                    <input
                      placeholder="Ej. 729-..."
                      value={historialFilters.awb}
                      onChange={e => setHistorialFilters({ ...historialFilters, awb: e.target.value })}
                      style={{ width: '100%', padding: '0.42rem 0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.78rem', boxSizing: 'border-box' }}
                    />
                  </div>
                </div>

                {/* Barra de Acciones de Filtro (Botones Exportar, Limpiar, Aplicar) */}
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.65rem', marginTop: '0.85rem', paddingTop: '0.75rem', borderTop: '1px solid #f1f5f9', alignItems: 'center' }}>
                  <button
                    type="button"
                    onClick={handleExportHistorialExcel}
                    style={{ background: '#16a34a', border: 'none', borderRadius: '6px', padding: '0.45rem 1.1rem', fontSize: '0.82rem', fontWeight: 800, color: '#ffffff', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.4rem', boxShadow: '0 2px 6px rgba(22,163,74,0.3)' }}
                    title="Exportar Historial de Compras a Excel"
                  >
                    📥 Exportar a Excel
                  </button>
                  <button
                    type="button"
                    onClick={handleClearHistorialFilters}
                    style={{ background: '#f8fafc', border: '1px solid #cbd5e1', borderRadius: '6px', padding: '0.45rem 1rem', fontSize: '0.8rem', fontWeight: 700, color: '#475569', cursor: 'pointer' }}
                  >
                    🧹 Limpiar Filtros
                  </button>
                  <button
                    type="submit"
                    style={{ background: '#1c5236', border: 'none', borderRadius: '6px', padding: '0.45rem 1.4rem', fontSize: '0.85rem', fontWeight: 800, color: '#ffffff', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.4rem', boxShadow: '0 2px 6px rgba(28,82,54,0.3)' }}
                  >
                    🔍 Aplicar Filtros
                  </button>
                </div>
              </form>
            </div>

            {/* Selection Bulk Action Bar */}
            {selectedHistorialIds.size > 0 && (
              <div style={{ background: '#f0fdf4', border: '1px solid #86efac', padding: '0.75rem 1.25rem', borderRadius: '10px', marginBottom: '1rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '0.75rem' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                  <span style={{ fontWeight: 800, color: '#166534', fontSize: '0.9rem' }}>
                    ✓ {selectedHistorialIds.size} {selectedHistorialIds.size === 1 ? 'caja seleccionada' : 'cajas seleccionadas'}
                  </span>
                  <button
                    type="button"
                    onClick={() => setSelectedHistorialIds(new Set())}
                    style={{ background: 'transparent', border: 'none', color: '#64748b', textDecoration: 'underline', cursor: 'pointer', fontSize: '0.8rem' }}
                  >
                    Deseleccionar
                  </button>
                </div>
                <div style={{ display: 'flex', gap: '0.6rem' }}>
                  {isFarmUser ? (
                    <button
                      type="button"
                      onClick={() => {
                        window.open(`/pedidos/print-labels/batch?ids=${Array.from(selectedHistorialIds).join(',')}`, '_blank');
                      }}
                      style={{ padding: '0.45rem 1.1rem', borderRadius: '6px', border: '1px solid #16a34a', background: '#16a34a', color: '#fff', fontWeight: 800, fontSize: '0.82rem', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.4rem', boxShadow: '0 2px 4px rgba(22,163,74,0.3)' }}
                    >
                      🏷️ Descargar Etiquetas ({selectedHistorialIds.size})
                    </button>
                  ) : (
                    <>
                      <button
                        type="button"
                        onClick={() => handleOpenEditFromLines(Array.from(selectedHistorialIds))}
                        style={{ padding: '0.45rem 1rem', borderRadius: '6px', border: '1px solid #2563eb', background: '#2563eb', color: '#fff', fontWeight: 700, fontSize: '0.82rem', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.4rem' }}
                      >
                        ✏️ Editar Orden ({selectedHistorialIds.size})
                      </button>
                      <button
                        type="button"
                        onClick={() => handleCancelHistorialLines(Array.from(selectedHistorialIds))}
                        style={{ padding: '0.45rem 1rem', borderRadius: '6px', border: '1px solid #dc2626', background: '#dc2626', color: '#fff', fontWeight: 700, fontSize: '0.82rem', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '0.4rem' }}
                      >
                        ❌ Cancelar Orden ({selectedHistorialIds.size})
                      </button>
                    </>
                  )}
                </div>
              </div>
            )}

            {/* TABLA PRINCIPAL DE HISTORIAL */}
            <div style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 4px 12px rgba(0,0,0,0.06)', overflowX: 'auto', border: '1px solid #e5e7eb' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem', textAlign: 'left', minWidth: historialViewMode === 'GROUPED' ? '1280px' : (isFarmUser ? '1100px' : '1350px') }}>
                <thead>
                  <tr style={{ background: '#1c5236', color: '#fff' }}>
                    <th style={{ padding: '0.75rem 0.6rem', textAlign: 'center', width: '36px' }}>
                      <input
                        type="checkbox"
                        checked={filteredPurchasedLines.length > 0 && selectedHistorialIds.size >= filteredPurchasedLines.length}
                        onChange={toggleSelectAllHistorial}
                        title="Seleccionar todas las órdenes"
                        style={{ cursor: 'pointer' }}
                      />
                    </th>
                    {historialViewMode === 'GROUPED' ? (
                      <>
                        <th style={{ padding: '0.75rem 0.8rem' }}>FINCA</th>
                        <th style={{ padding: '0.75rem 0.8rem' }}>ITEM</th>
                        <th style={{ padding: '0.75rem 0.8rem' }}>PRODUCTO</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'right' }}>PRECIO</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>FECHA SALIDA FINCA</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>SHIPDATE</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>DELIVERY</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>AGENCIA</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>GUIA AEREA</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>CANTIDAD ORDENADA</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>CANTIDAD ACTUAL</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>CANTIDAD CANCELADA</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>TIPO DE CAJA</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>ESTADO</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>ACCIONES</th>
                      </>
                    ) : (
                      <>
                        {!isFarmUser && <th style={{ padding: '0.75rem 0.8rem' }}>CLIENTE</th>}
                        <th style={{ padding: '0.75rem 0.8rem' }}>FINCA</th>
                        <th style={{ padding: '0.75rem 0.8rem' }}>ITEM</th>
                        <th style={{ padding: '0.75rem 0.8rem' }}>PRODUCTO</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'right' }}>PRECIO ($)</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>FECHA SALIDA FINCA</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>SHIPDATE</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>DELIVERY</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>AGENCIA</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>GUÍA AÉREA</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>BOX / CÓDIGOS</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>ESTADO</th>
                        <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>
                          {isFarmUser ? 'DESCARGAR ETIQUETAS' : 'ACCIONES'}
                        </th>
                      </>
                    )}
                  </tr>
                </thead>
                <tbody>
                  {/* Vista Agrupada por Totales */}
                  {historialViewMode === 'GROUPED' ? (
                    historialGroups.length === 0 ? (
                      <tr>
                        <td colSpan={16} style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>
                          No hay compras registradas con los filtros aplicados.
                        </td>
                      </tr>
                    ) : (
                      historialDispatchGroups.map(dispatch => {
                        const sumOrdered = dispatch.groups.reduce((acc, g) => acc + g.qtyOrdered, 0);
                        const sumCancelled = dispatch.groups.reduce((acc, g) => acc + g.cancelledCount, 0);
                        return (
                          <React.Fragment key={`dispatch-grp-${dispatch.key}`}>
                            {/* Despacho Banner Header */}
                            <tr style={{ background: '#f0fdf4', borderTop: '2px solid #16a34a', borderBottom: '1px solid #bbf7d0' }}>
                              <td colSpan={16} style={{ padding: '0.65rem 1rem' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '0.75rem' }}>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '1.25rem', flexWrap: 'wrap' }}>
                                    <span style={{ fontWeight: 800, color: '#166534', fontSize: '0.88rem' }}>
                                      🚚 DESPACHO:
                                    </span>
                                    <span style={{ fontSize: '0.84rem', color: '#1e293b' }}>
                                      <strong>Finca:</strong> <span style={{ color: '#047857', fontWeight: 800 }}>{dispatch.farmName}</span>
                                    </span>
                                    <span style={{ fontSize: '0.84rem', color: '#1e293b' }}>
                                      <strong>Shipdate:</strong> <span style={{ fontFamily: 'monospace', fontWeight: 700 }}>{dispatch.shipdt || '—'}</span>
                                    </span>
                                    <span style={{ fontSize: '0.84rem', color: '#1e293b' }}>
                                      <strong>Salida Finca:</strong> <span style={{ fontFamily: 'monospace' }}>{dispatch.farmDepartureDate || '—'}</span>
                                    </span>
                                    <span style={{ fontSize: '0.84rem', color: '#1e293b' }}>
                                      <strong>Agencia:</strong> <span style={{ color: '#0f766e', fontWeight: 700 }}>{dispatch.agency || '—'}</span>
                                    </span>
                                    <span style={{ fontSize: '0.92rem', color: '#1e293b', background: '#eff6ff', padding: '0.2rem 0.65rem', borderRadius: '6px', border: '1px solid #bfdbfe' }}>
                                      <strong>Guía AWB:</strong> <span style={{ color: '#2563eb', fontWeight: 900, fontFamily: 'monospace', fontSize: '1rem', letterSpacing: '0.04em' }}>{dispatch.awb || '—'}</span>
                                    </span>
                                    <span style={{ background: '#dcfce7', color: '#166534', padding: '0.2rem 0.65rem', borderRadius: '12px', fontSize: '0.8rem', fontWeight: 800, border: '1px solid #86efac' }}>
                                      Total Despacho: {dispatch.totalBoxes} cajas (${dispatch.totalPrice.toFixed(2)})
                                    </span>
                                  </div>
                                </div>
                              </td>
                            </tr>

                            {/* Filas del Despacho (16 columnas exactas) */}
                            {dispatch.groups.map(group => {
                              const isGroupSelected = group.lineIds.every(id => selectedHistorialIds.has(id));
                              return (
                                <tr key={group.groupKey} style={{ borderBottom: '1px solid #f1f5f9', background: isGroupSelected ? '#f0fdf4' : '#fff' }}>
                                  <td style={{ padding: '0.6rem 0.6rem', textAlign: 'center' }}>
                                    <input
                                      type="checkbox"
                                      checked={isGroupSelected}
                                      onChange={() => toggleSelectHistorialGroup(group.lineIds)}
                                      style={{ cursor: 'pointer' }}
                                    />
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', fontWeight: 700, color: '#1e293b' }}>
                                    {group.farmName}
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', fontFamily: 'monospace', fontWeight: 800, color: '#dc2626' }}>
                                    {group.item}
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', fontWeight: 500, color: '#1e293b' }}>
                                    {group.prodDesc}
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'right', fontWeight: 700 }}>
                                    ${(group.farmPrice || 0).toFixed(2)}
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>
                                    {group.farmDepartureDate || '—'}
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>
                                    {group.shipdt || '—'}
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>
                                    {group.deliver || '—'}
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontWeight: 700, color: '#0f766e' }}>
                                    {group.agency || '—'}
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 700, color: '#2563eb' }}>
                                    {group.awb || '—'}
                                  </td>
                                  {/* CANTIDAD ORDENADA */}
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontWeight: 800, color: '#1e293b', fontSize: '0.9rem' }}>
                                    {group.qtyOrdered}
                                  </td>
                                  {/* CANTIDAD ACTUAL */}
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontWeight: 800, color: '#166534', fontSize: '0.9rem' }}>
                                    {group.qtyActual}
                                  </td>
                                  {/* CANTIDAD CANCELADA */}
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>
                                    {group.cancelledCount > 0 ? (
                                      <span style={{ background: '#fee2e2', color: '#dc2626', padding: '0.2rem 0.55rem', borderRadius: '8px', fontSize: '0.78rem', fontWeight: 800, border: '1px solid #fca5a5' }}>
                                        ❌ {group.cancelledCount}
                                      </span>
                                    ) : (
                                      <span style={{ color: '#94a3b8' }}>0</span>
                                    )}
                                  </td>
                                  {/* TIPO DE CAJA */}
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>
                                    <span style={{
                                      background: '#f8fafc',
                                      color: '#1e293b',
                                      padding: '0.25rem 0.6rem',
                                      borderRadius: '6px',
                                      fontSize: '0.8rem',
                                      fontWeight: 700,
                                      border: '1px solid #cbd5e1',
                                      display: 'inline-block'
                                    }}>
                                      {group.boxType || '—'}
                                    </span>
                                  </td>
                                  {/* ESTADO */}
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>
                                    <span style={{ background: '#dbeafe', color: '#1e40af', padding: '0.2rem 0.6rem', borderRadius: '10px', fontSize: '0.75rem', fontWeight: 700 }}>
                                      {group.status}
                                    </span>
                                  </td>
                                  {/* ACCIONES (ICONOS PARA AHORRAR ESPACIO VISUAL) */}
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>
                                    <div style={{ display: 'flex', gap: '0.4rem', justifyContent: 'center' }}>
                                      <button
                                        type="button"
                                        onClick={() => handleOpenEditFromGroups([group])}
                                        style={{ padding: '0.25rem 0.45rem', borderRadius: '4px', border: '1px solid #3b82f6', background: '#eff6ff', color: '#1d4ed8', cursor: 'pointer', fontSize: '0.85rem' }}
                                        title="Editar orden"
                                      >
                                        ✏️
                                      </button>
                                      <button
                                        type="button"
                                        onClick={() => handleCancelHistorialLines(group.lineIds)}
                                        style={{ padding: '0.25rem 0.45rem', borderRadius: '4px', border: '1px solid #fca5a5', background: '#fef2f2', color: '#b91c1c', cursor: 'pointer', fontSize: '0.85rem' }}
                                        title="Cancelar orden"
                                      >
                                        ❌
                                      </button>
                                    </div>
                                  </td>
                                </tr>
                              );
                            })}

                            {/* Subtotal del Despacho por Finca, Salida Finca y Guía Aérea con Botón de Imprimir y Protección de Duplicación */}
                            <tr style={{ background: '#f8fafc', fontWeight: 800, borderBottom: '2px solid #cbd5e1', color: '#334155' }}>
                              <td colSpan={10} style={{ padding: '0.65rem 1rem', textAlign: 'right', color: '#475569' }}>
                                Subtotal Finca: <strong style={{ color: '#047857' }}>{dispatch.farmName}</strong> &bull; Salida: <span style={{ fontFamily: 'monospace' }}>{dispatch.farmDepartureDate}</span> &bull; AWB: <span style={{ color: '#2563eb', fontFamily: 'monospace' }}>{dispatch.awb}</span>:
                              </td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', color: '#1e293b', fontSize: '0.9rem' }}>
                                {sumOrdered}
                              </td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', color: '#166534', fontSize: '0.92rem' }}>
                                {dispatch.totalBoxes}
                              </td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', color: '#dc2626' }}>
                                {sumCancelled}
                              </td>
                              <td colSpan={3} style={{ padding: '0.65rem 1rem', textAlign: 'right' }}>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '0.75rem', flexWrap: 'wrap' }}>
                                  <span style={{ color: '#166534', fontWeight: 800, fontSize: '0.88rem' }}>
                                    Total: ${dispatch.totalPrice.toFixed(2)}
                                  </span>
                                  {dispatch.allReceived ? (
                                    <button
                                      type="button"
                                      disabled
                                      style={{
                                        background: '#94a3b8',
                                        color: '#fff',
                                        border: 'none',
                                        borderRadius: '6px',
                                        padding: '0.4rem 0.85rem',
                                        fontSize: '0.78rem',
                                        fontWeight: 800,
                                        cursor: 'not-allowed',
                                        display: 'inline-flex',
                                        alignItems: 'center',
                                        gap: '0.35rem'
                                      }}
                                      title="Cajas ya recibidas en cuarto frío — Etiquetas inhabilitadas para evitar duplicación"
                                    >
                                      🔒 Recibido (Etiquetas Inhabilitadas)
                                    </button>
                                  ) : (
                                    <button
                                      type="button"
                                      onClick={() => window.open(`/pedidos/print-labels/batch?ids=${dispatch.printableLineIds.join(',')}`, '_blank')}
                                      style={{
                                        background: '#16a34a',
                                        color: '#fff',
                                        border: 'none',
                                        borderRadius: '6px',
                                        padding: '0.4rem 0.85rem',
                                        fontSize: '0.78rem',
                                        fontWeight: 800,
                                        cursor: 'pointer',
                                        display: 'inline-flex',
                                        alignItems: 'center',
                                        gap: '0.35rem',
                                        boxShadow: '0 2px 4px rgba(22,163,74,0.3)'
                                      }}
                                      title={dispatch.hasReceived ? `Imprimir ${dispatch.printableLineIds.length} etiquetas pendientes` : `Imprimir las ${dispatch.totalBoxes} etiquetas de este despacho`}
                                    >
                                      🖨️ Imprimir Etiquetas ({dispatch.printableLineIds.length})
                                    </button>
                                  )}
                                </div>
                              </td>
                            </tr>
                          </React.Fragment>
                        );
                      })
                    )
                  ) : (
                    /* Vista Individual por Caja */
                    filteredPurchasedLines.length === 0 ? (
                      <tr>
                        <td colSpan={isFarmUser ? 12 : 15} style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>
                          No hay cajas asignadas con los filtros aplicados.
                        </td>
                      </tr>
                    ) : (
                      historialDispatchGroups.map(dispatch => {
                        return (
                          <React.Fragment key={`dispatch-lines-${dispatch.key}`}>
                            {/* Despacho Banner Header */}
                            <tr style={{ background: '#f0fdf4', borderTop: '2px solid #16a34a', borderBottom: '1px solid #bbf7d0' }}>
                              <td colSpan={isFarmUser ? 13 : 14} style={{ padding: '0.65rem 1rem' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '0.75rem' }}>
                                  <div style={{ display: 'flex', alignItems: 'center', gap: '1.25rem', flexWrap: 'wrap' }}>
                                    <span style={{ fontWeight: 800, color: '#166534', fontSize: '0.88rem' }}>
                                      🚚 DESPACHO:
                                    </span>
                                    <span style={{ fontSize: '0.84rem', color: '#1e293b' }}>
                                      <strong>Finca:</strong> <span style={{ color: '#047857', fontWeight: 800 }}>{dispatch.farmName}</span>
                                    </span>
                                    <span style={{ fontSize: '0.84rem', color: '#1e293b' }}>
                                      <strong>Shipdate:</strong> <span style={{ fontFamily: 'monospace', fontWeight: 700 }}>{dispatch.shipdt || '—'}</span>
                                    </span>
                                    <span style={{ fontSize: '0.84rem', color: '#1e293b' }}>
                                      <strong>Salida Finca:</strong> <span style={{ fontFamily: 'monospace' }}>{dispatch.farmDepartureDate || '—'}</span>
                                    </span>
                                    <span style={{ fontSize: '0.84rem', color: '#1e293b' }}>
                                      <strong>Agencia:</strong> <span style={{ color: '#0f766e', fontWeight: 700 }}>{dispatch.agency || '—'}</span>
                                    </span>
                                    <span style={{ fontSize: '0.92rem', color: '#1e293b', background: '#eff6ff', padding: '0.2rem 0.65rem', borderRadius: '6px', border: '1px solid #bfdbfe' }}>
                                      <strong>Guía AWB:</strong> <span style={{ color: '#2563eb', fontWeight: 900, fontFamily: 'monospace', fontSize: '1rem', letterSpacing: '0.04em' }}>{dispatch.awb || '—'}</span>
                                    </span>
                                    <span style={{ background: '#dcfce7', color: '#166534', padding: '0.2rem 0.65rem', borderRadius: '12px', fontSize: '0.8rem', fontWeight: 800, border: '1px solid #86efac' }}>
                                      Total Despacho: {dispatch.totalBoxes} cajas (${dispatch.totalPrice.toFixed(2)})
                                    </span>
                                  </div>
                                </div>
                              </td>
                            </tr>

                            {/* Filas Individuales del Despacho */}
                            {dispatch.individualLines.map(line => {
                              const isSelected = selectedHistorialIds.has(line.id);
                              return (
                                <tr key={line.id} style={{ borderBottom: '1px solid #f1f5f9', background: isSelected ? '#f0fdf4' : '#fff' }}>
                                  <td style={{ padding: '0.6rem 0.6rem', textAlign: 'center' }}>
                                    <input
                                      type="checkbox"
                                      checked={isSelected}
                                      onChange={() => toggleSelectHistorialLine(line.id)}
                                      style={{ cursor: 'pointer' }}
                                    />
                                  </td>
                                  {!isFarmUser && (
                                    <td style={{ padding: '0.6rem 0.8rem', color: '#334155', fontWeight: 600 }}>
                                      <div>{line.customerName}</div>
                                      {line.po && <div style={{ fontSize: '0.72rem', color: '#64748b' }}>PO: {line.po}</div>}
                                    </td>
                                  )}
                                  {!isFarmUser && (
                                    <td style={{ padding: '0.6rem 0.8rem', fontWeight: 700, color: '#1e293b' }}>{line.farmName}</td>
                                  )}
                                  <td style={{ padding: '0.6rem 0.8rem', fontFamily: 'monospace', fontWeight: 800, color: '#dc2626' }}>{line.item}</td>
                                  <td style={{ padding: '0.6rem 0.8rem' }}>{line.prodDesc}</td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'right', fontWeight: 700 }}>${(line.farmPrice || 0).toFixed(2)}</td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 600 }}>{line.orddate || '—'}</td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>{line.farmDepartureDate || '—'}</td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>{line.shipdt || '—'}</td>
                                  {!isFarmUser && (
                                    <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>{line.deliver || '—'}</td>
                                  )}
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontWeight: 700, color: '#0f766e' }}>{line.agency || '—'}</td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 700, color: '#2563eb' }}>{line.awb || '—'}</td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>
                                    <span style={{ fontWeight: 800, color: '#2563eb' }}>{line.boxNumber || '—'}</span>
                                    <span style={{ fontSize: '0.72rem', color: '#64748b', display: 'block' }}>{line.boxType}</span>
                                    {line.uniqueCode && (
                                      <span style={{ fontSize: '0.68rem', color: '#475569', display: 'block', wordBreak: 'break-all' }}>
                                        {line.uniqueCode}
                                      </span>
                                    )}
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>
                                    <span style={{ background: '#dbeafe', color: '#1e40af', padding: '0.2rem 0.6rem', borderRadius: '10px', fontSize: '0.75rem', fontWeight: 700 }}>
                                      {line.status}
                                    </span>
                                  </td>
                                  <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>
                                    <div style={{ display: 'flex', gap: '0.35rem', justifyContent: 'center' }}>
                                      {isFarmUser ? (
                                        <button
                                          type="button"
                                          onClick={() => {
                                            window.open(`/pedidos/print-labels/${line.id}`, '_blank');
                                          }}
                                          style={{
                                            padding: '0.3rem 0.7rem',
                                            borderRadius: '6px',
                                            border: '1px solid #16a34a',
                                            background: '#16a34a',
                                            color: '#fff',
                                            cursor: 'pointer',
                                            fontSize: '0.75rem',
                                            fontWeight: 800,
                                            display: 'inline-flex',
                                            alignItems: 'center',
                                            gap: '0.25rem',
                                            boxShadow: '0 2px 4px rgba(22,163,74,0.25)'
                                          }}
                                          title="Descargar etiqueta de esta caja"
                                        >
                                          🏷️ Descargar Etiqueta
                                        </button>
                                      ) : (
                                        <>
                                          <button
                                            type="button"
                                            onClick={() => handleOpenEditFromLines([line.id])}
                                            style={{ padding: '0.25rem 0.55rem', borderRadius: '4px', border: '1px solid #3b82f6', background: '#eff6ff', color: '#1d4ed8', cursor: 'pointer', fontSize: '0.75rem', fontWeight: 700 }}
                                            title="Editar orden"
                                          >
                                            ✏️ Editar
                                          </button>
                                          <button
                                            type="button"
                                            onClick={() => handleCancelHistorialLines([line.id])}
                                            style={{ padding: '0.25rem 0.55rem', borderRadius: '4px', border: '1px solid #fca5a5', background: '#fef2f2', color: '#b91c1c', cursor: 'pointer', fontSize: '0.75rem', fontWeight: 700 }}
                                            title="Cancelar orden"
                                          >
                                            ❌ Cancelar
                                          </button>
                                        </>
                                      )}
                                    </div>
                                  </td>
                                </tr>
                              );
                            })}

                            {/* Subtotal del Despacho por Finca, Salida Finca y Guía Aérea en Modo Individual */}
                            <tr style={{ background: '#f8fafc', fontWeight: 800, borderBottom: '2px solid #cbd5e1', color: '#334155' }}>
                              <td colSpan={isFarmUser ? 9 : 10} style={{ padding: '0.65rem 1rem', textAlign: 'right', color: '#475569' }}>
                                Subtotal Finca: <strong style={{ color: '#047857' }}>{dispatch.farmName}</strong> &bull; Salida: <span style={{ fontFamily: 'monospace' }}>{dispatch.farmDepartureDate}</span> &bull; AWB: <span style={{ color: '#2563eb', fontFamily: 'monospace' }}>{dispatch.awb}</span>:
                              </td>
                              <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center', color: '#166534', fontSize: '0.92rem' }}>
                                {dispatch.totalBoxes} cajas
                              </td>
                              <td colSpan={3} style={{ padding: '0.65rem 1rem', textAlign: 'right' }}>
                                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '0.75rem', flexWrap: 'wrap' }}>
                                  <span style={{ color: '#166534', fontWeight: 800, fontSize: '0.88rem' }}>
                                    Total: ${dispatch.totalPrice.toFixed(2)}
                                  </span>
                                  {dispatch.allReceived ? (
                                    <button
                                      type="button"
                                      disabled
                                      style={{
                                        background: '#94a3b8',
                                        color: '#fff',
                                        border: 'none',
                                        borderRadius: '6px',
                                        padding: '0.4rem 0.85rem',
                                        fontSize: '0.78rem',
                                        fontWeight: 800,
                                        cursor: 'not-allowed',
                                        display: 'inline-flex',
                                        alignItems: 'center',
                                        gap: '0.35rem'
                                      }}
                                      title="Cajas ya recibidas en cuarto frío — Etiquetas inhabilitadas para evitar duplicación"
                                    >
                                      🔒 Recibido (Etiquetas Inhabilitadas)
                                    </button>
                                  ) : (
                                    <button
                                      type="button"
                                      onClick={() => window.open(`/pedidos/print-labels/batch?ids=${dispatch.printableLineIds.join(',')}`, '_blank')}
                                      style={{
                                        background: '#16a34a',
                                        color: '#fff',
                                        border: 'none',
                                        borderRadius: '6px',
                                        padding: '0.4rem 0.85rem',
                                        fontSize: '0.78rem',
                                        fontWeight: 800,
                                        cursor: 'pointer',
                                        display: 'inline-flex',
                                        alignItems: 'center',
                                        gap: '0.35rem',
                                        boxShadow: '0 2px 4px rgba(22,163,74,0.3)'
                                      }}
                                      title={dispatch.hasReceived ? `Imprimir ${dispatch.printableLineIds.length} etiquetas pendientes` : `Imprimir las ${dispatch.totalBoxes} etiquetas de este despacho`}
                                    >
                                      🖨️ Imprimir Etiquetas ({dispatch.printableLineIds.length})
                                    </button>
                                  )}
                                </div>
                              </td>
                            </tr>
                          </React.Fragment>
                        );
                      })
                    )
                  )}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* ── TAB 4: RECHAZOS QC Y AJUSTES FINCA ─────────────────────────────── */}
        {activeTab === 'RECHAZOS' && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', flexWrap: 'wrap', gap: '1rem' }}>
              <div>
                <h2 style={{ margin: 0, fontSize: '1.4rem', fontWeight: 800, color: '#dc2626' }}>
                  ⚠️ Registro de Rechazos QC y Correcciones de Factura a Fincas
                </h2>
                <p style={{ margin: '0.2rem 0 0', color: '#666', fontSize: '0.85rem' }}>
                  Cajas rechazadas en Cuarto Frío que regresaron a estado NEW para reordenar, generando descuento para la factura de la finca.
                </p>
              </div>
              <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
                <div style={{ background: '#fee2e2', border: '1px solid #fca5a5', padding: '0.5rem 1rem', borderRadius: '8px', color: '#991b1b', fontWeight: 700, fontSize: '0.9rem' }}>
                  Total a Descontar: ${displayedRejections.reduce((acc, r) => acc + (r.price || 0), 0).toFixed(2)}
                </div>
                <button
                  type="button"
                  onClick={handleExportRejectionsExcel}
                  style={{ background: '#16a34a', border: 'none', borderRadius: '8px', padding: '0.55rem 1.1rem', color: '#fff', cursor: 'pointer', fontWeight: 800, fontSize: '0.85rem', display: 'flex', alignItems: 'center', gap: '0.4rem', boxShadow: '0 2px 6px rgba(22,163,74,0.3)' }}
                  title="Exportar Rechazos QC a Excel"
                >
                  📥 Exportar a Excel
                </button>
              </div>
            </div>

            <div style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 4px 12px rgba(0,0,0,0.06)', overflowX: 'auto', border: '1px solid #e5e7eb' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.85rem', textAlign: 'left' }}>
                <thead>
                  <tr style={{ background: '#991b1b', color: '#fff' }}>
                    <th style={{ padding: '0.85rem 1rem' }}>FINCA</th>
                    <th style={{ padding: '0.85rem 1rem' }}>FECHA RECHAZO</th>
                    <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>BOX#</th>
                    <th style={{ padding: '0.85rem 1rem' }}>PRODUCTO</th>
                    <th style={{ padding: '0.85rem 1rem' }}>MOTIVO / RAZÓN</th>
                    <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>FOTO / EVIDENCIA</th>
                    <th style={{ padding: '0.85rem 1rem', textAlign: 'right' }}>VALOR DESCUENTO</th>
                    <th style={{ padding: '0.85rem 1rem', textAlign: 'center' }}>ESTADO</th>
                  </tr>
                </thead>
                <tbody>
                  {displayedRejections.length === 0 ? (
                    <tr>
                      <td colSpan={8} style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>
                        No hay cajas rechazadas por QC registradas.
                      </td>
                    </tr>
                  ) : (
                    displayedRejections.map(rej => (
                      <tr key={rej.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                        <td style={{ padding: '0.75rem 1rem', fontWeight: 800, color: '#1e293b' }}>
                          {rej.farm?.name || '—'}
                          {rej.farm?.ruc && <span style={{ display: 'block', fontSize: '0.72rem', color: '#64748b' }}>RUC: {rej.farm.ruc}</span>}
                        </td>
                        <td style={{ padding: '0.75rem 1rem', color: '#475569' }}>
                          {new Date(rej.createdAt).toLocaleString('es-EC')}
                        </td>
                        <td style={{ padding: '0.75rem 1rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 800, color: '#dc2626' }}>
                          {rej.boxNumber || '—'}
                        </td>
                        <td style={{ padding: '0.75rem 1rem' }}>
                          <span style={{ fontWeight: 700, color: '#1e293b' }}>{rej.productName || '—'}</span>
                          <span style={{ display: 'block', fontSize: '0.75rem', fontFamily: 'monospace', color: '#64748b' }}>{rej.productCode}</span>
                        </td>
                        <td style={{ padding: '0.75rem 1rem', color: '#b91c1c', fontWeight: 600 }}>
                          {rej.reason}
                        </td>
                        <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>
                          {rej.photoUrl ? (
                            <button
                              onClick={() => {
                                const w = window.open('');
                                if (w) w.document.write(`<img src="${rej.photoUrl}" style="max-width:100%"/>`);
                              }}
                              style={{ padding: '0.25rem 0.6rem', borderRadius: '4px', border: '1px solid #cbd5e1', background: '#f8fafc', cursor: 'pointer', fontSize: '0.75rem' }}
                            >
                              📷 Ver Foto
                            </button>
                          ) : (
                            <span style={{ color: '#9ca3af', fontSize: '0.75rem' }}>Sin foto</span>
                          )}
                        </td>
                        <td style={{ padding: '0.75rem 1rem', textAlign: 'right', fontWeight: 900, color: '#dc2626' }}>
                          -${(rej.price || 0).toFixed(2)}
                        </td>
                        <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>
                          <span style={{ background: '#fee2e2', color: '#991b1b', padding: '0.2rem 0.6rem', borderRadius: '10px', fontSize: '0.75rem', fontWeight: 700 }}>
                            Descuento Aplicado
                          </span>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* ── TAB 5: ETIQUETAS Y CAJAS CANCELADAS ─────────────────────────── */}
        {activeTab === 'CANCELADAS' && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', flexWrap: 'wrap', gap: '1rem' }}>
              <div>
                <h2 style={{ margin: 0, fontSize: '1.4rem', fontWeight: 800, color: '#dc2626', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                  🚫 Registro de Etiquetas y Cajas Canceladas
                </h2>
                <p style={{ margin: '0.2rem 0 0', color: '#64748b', fontSize: '0.85rem' }}>
                  Listado de códigos únicos inhabilitados y cajas canceladas por ajustes o reducción de cantidades. Ningún código cancelado puede ser reutilizado.
                </p>
              </div>
              <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
                <input
                  placeholder="🔍 Buscar por código, box, finca, item..."
                  value={historialSearchCancelled}
                  onChange={e => setHistorialSearchCancelled(e.target.value)}
                  style={{ padding: '0.45rem 0.8rem', border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.82rem', width: '280px' }}
                />
                <button
                  type="button"
                  onClick={handleExportCancelledExcel}
                  style={{ background: '#16a34a', border: 'none', borderRadius: '8px', padding: '0.45rem 1rem', color: '#fff', cursor: 'pointer', fontWeight: 800, fontSize: '0.82rem', display: 'flex', alignItems: 'center', gap: '0.4rem', boxShadow: '0 2px 6px rgba(22,163,74,0.3)' }}
                  title="Exportar Etiquetas Canceladas a Excel"
                >
                  📥 Exportar a Excel
                </button>
              </div>
            </div>

            <div style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 4px 12px rgba(0,0,0,0.06)', overflowX: 'auto', border: '1px solid #e5e7eb' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.82rem', textAlign: 'left', minWidth: '1100px' }}>
                <thead>
                  <tr style={{ background: '#991b1b', color: '#fff' }}>
                    <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>ESTADO</th>
                    <th style={{ padding: '0.75rem 0.8rem' }}>CÓDIGO ÚNICO</th>
                    <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>BOX #</th>
                    <th style={{ padding: '0.75rem 0.8rem' }}>ITEM / PRODUCTO</th>
                    <th style={{ padding: '0.75rem 0.8rem' }}>FINCA</th>
                    <th style={{ padding: '0.75rem 0.8rem' }}>CLIENTE / PO</th>
                    <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>GUÍA AÉREA</th>
                    <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>FECHA CANCELACIÓN</th>
                    <th style={{ padding: '0.75rem 0.8rem' }}>MOTIVO</th>
                    <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center' }}>ACCIONES</th>
                  </tr>
                </thead>
                <tbody>
                  {displayedCancelledLabels.filter(c => {
                    if (!historialSearchCancelled) return true;
                    const q = historialSearchCancelled.toLowerCase();
                    return `${c.uniqueCode} ${c.boxNumber} ${c.itemCode} ${c.productName} ${c.farmName || ''} ${c.customerName || ''} ${c.po || ''} ${c.airwayBill || ''}`.toLowerCase().includes(q);
                  }).length === 0 ? (
                    <tr>
                      <td colSpan={10} style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>
                        No hay etiquetas canceladas registradas.
                      </td>
                    </tr>
                  ) : (
                    displayedCancelledLabels.filter(c => {
                      if (!historialSearchCancelled) return true;
                      const q = historialSearchCancelled.toLowerCase();
                      return `${c.uniqueCode} ${c.boxNumber} ${c.itemCode} ${c.productName} ${c.farmName || ''} ${c.customerName || ''} ${c.po || ''} ${c.airwayBill || ''}`.toLowerCase().includes(q);
                    }).map(c => (
                      <tr key={c.id} style={{ borderBottom: '1px solid #f1f5f9', background: '#fff' }}>
                        <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>
                          <span style={{ background: '#fee2e2', color: '#dc2626', padding: '0.2rem 0.6rem', borderRadius: '10px', fontSize: '0.75rem', fontWeight: 800, border: '1px solid #fca5a5' }}>
                            🚫 CANCELADO
                          </span>
                        </td>
                        <td style={{ padding: '0.6rem 0.8rem', fontFamily: 'monospace', fontWeight: 800, color: '#dc2626', fontSize: '0.82rem' }}>
                          {c.uniqueCode}
                        </td>
                        <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>
                          <span style={{ fontWeight: 800, color: '#1e293b' }}>#{c.boxNumber}</span>
                          {c.boxType && <span style={{ fontSize: '0.72rem', color: '#64748b', display: 'block' }}>{c.boxType}</span>}
                        </td>
                        <td style={{ padding: '0.6rem 0.8rem' }}>
                          <span style={{ fontWeight: 800, color: '#1e293b', fontFamily: 'monospace' }}>{c.itemCode}</span>
                          <span style={{ display: 'block', fontSize: '0.75rem', color: '#475569' }}>{c.productName}</span>
                        </td>
                        <td style={{ padding: '0.6rem 0.8rem', fontWeight: 700, color: '#1e293b' }}>
                          {c.farmName || '—'}
                        </td>
                        <td style={{ padding: '0.6rem 0.8rem', color: '#334155' }}>
                          <div>{c.customerName || '—'}</div>
                          {c.po && <div style={{ fontSize: '0.72rem', color: '#64748b' }}>PO: {c.po}</div>}
                        </td>
                        <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontFamily: 'monospace' }}>
                          {c.airwayBill || '—'}
                        </td>
                        <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center', fontSize: '0.78rem', color: '#475569' }}>
                          {new Date(c.cancelledAt).toLocaleString('es-EC')}
                        </td>
                        <td style={{ padding: '0.6rem 0.8rem', fontSize: '0.75rem', color: '#b91c1c' }}>
                          {c.reason || 'Cancelación de orden'}
                        </td>
                        <td style={{ padding: '0.6rem 0.8rem', textAlign: 'center' }}>
                          <a
                            href={`/pedidos/print-labels/${c.id}?cancelled=true`}
                            target="_blank"
                            rel="noopener noreferrer"
                            style={{
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: '0.3rem',
                              padding: '0.25rem 0.6rem',
                              borderRadius: '4px',
                              border: '1px solid #fca5a5',
                              background: '#fef2f2',
                              color: '#dc2626',
                              textDecoration: 'none',
                              fontSize: '0.75rem',
                              fontWeight: 700
                            }}
                            title="Ver etiqueta con marca CANCELADO"
                          >
                            🖨️ Ver Etiqueta
                          </a>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>

      {/* ── MODAL: NUEVA / EDITAR GUÍA AÉREA ─────────────────────────────── */}
      {guiaModalOpen && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: '1rem' }}>
          <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '480px', maxWidth: '95vw', boxShadow: '0 25px 50px rgba(0,0,0,0.3)' }}>
            <h2 style={{ margin: '0 0 1.25rem', fontSize: '1.3rem', color: '#1c5236', fontWeight: 800 }}>
              ✈️ {guiaEditingId ? 'Editar Guía AWB' : 'Nueva Guía AWB (Paso 2)'}
            </h2>
            <form onSubmit={handleSaveGuia}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem', marginBottom: '1.5rem' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.3rem', color: '#374151' }}>Agencia de Carga *</label>
                  <select
                    value={guiaForm.agency}
                    onChange={e => {
                      const newAgency = e.target.value;
                      const newShipDate = guiaForm.deliverDate ? calculateShipDate(guiaForm.deliverDate, newAgency) : guiaForm.shipDate;
                      setGuiaForm({ ...guiaForm, agency: newAgency, shipDate: newShipDate || guiaForm.shipDate });
                    }}
                    style={{ width: '100%', padding: '0.6rem', border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.9rem', fontWeight: 600 }}
                  >
                    <option value="FEDEX">FEDEX</option>
                    <option value="UPS">UPS</option>
                    <option value="FLOWERCARGO">FLOWERCARGO</option>
                    <option value="CHAMPION">CHAMPION</option>
                    <option value="LATAM">LATAM CARGO</option>
                    <option value="AVIANCA">AVIANCA CARGO</option>
                  </select>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.75rem' }}>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.3rem', color: '#374151' }}>Deliver Date *</label>
                    <input
                      type="date"
                      required
                      value={guiaForm.deliverDate}
                      onChange={e => {
                        const newDeliver = e.target.value;
                        const newShipDate = calculateShipDate(newDeliver, guiaForm.agency);
                        setGuiaForm({ ...guiaForm, deliverDate: newDeliver, shipDate: newShipDate || guiaForm.shipDate });
                      }}
                      style={{ width: '100%', padding: '0.55rem', border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.85rem', boxSizing: 'border-box' }}
                    />
                  </div>
                  <div>
                    <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.3rem', color: '#374151' }}>Ship Date *</label>
                    <input
                      type="date"
                      required
                      value={guiaForm.shipDate}
                      onChange={e => setGuiaForm({ ...guiaForm, shipDate: e.target.value })}
                      style={{ width: '100%', padding: '0.55rem', border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.85rem', boxSizing: 'border-box' }}
                    />
                  </div>
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.3rem', color: '#374151' }}>
                    AWB (Número de Guía) *
                  </label>
                  <input
                    required
                    placeholder="Ej. 729-45452022"
                    value={guiaForm.awb}
                    onChange={e => handleGuiaAwbChange(e.target.value)}
                    style={{ width: '100%', padding: '0.6rem', border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.95rem', fontWeight: 700, fontFamily: 'monospace', boxSizing: 'border-box' }}
                  />
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.3rem', color: '#374151' }}>
                    MASTER (Automático: Últimos 4 dígitos de la guía)
                  </label>
                  <input
                    value={guiaForm.master}
                    onChange={e => setGuiaForm({ ...guiaForm, master: e.target.value })}
                    placeholder="2022"
                    style={{ width: '100%', padding: '0.6rem', border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.95rem', fontWeight: 800, fontFamily: 'monospace', background: '#f8fafc', color: '#2563eb', boxSizing: 'border-box' }}
                  />
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, marginBottom: '0.3rem', color: '#374151' }}>Notas</label>
                  <input
                    value={guiaForm.notes}
                    onChange={e => setGuiaForm({ ...guiaForm, notes: e.target.value })}
                    placeholder="Notas opcionales..."
                    style={{ width: '100%', padding: '0.55rem', border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.85rem', boxSizing: 'border-box' }}
                  />
                </div>
              </div>

              {guiaError && <p style={{ color: '#dc2626', fontSize: '0.85rem', margin: '0 0 1rem' }}>{guiaError}</p>}

              <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
                <button
                  type="button"
                  onClick={() => setGuiaModalOpen(false)}
                  style={{ padding: '0.6rem 1.25rem', borderRadius: '8px', border: '1px solid #cbd5e1', background: '#fff', cursor: 'pointer' }}
                >
                  Cancelar
                </button>
                <button
                  type="submit"
                  disabled={savingGuia}
                  style={{ padding: '0.6rem 1.5rem', borderRadius: '8px', border: 'none', background: '#1c5236', color: '#fff', fontWeight: 700, cursor: 'pointer' }}
                >
                  {savingGuia ? 'Guardando...' : 'Guardar Guía'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ── MODAL: ÉXITO DE COMPRA / NOTA OBLIGATORIA ─────────────────────── */}
      {orderSuccessModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1100, padding: '1rem' }}>
          <div style={{ background: '#fff', borderRadius: '20px', padding: '2.25rem', width: '600px', maxWidth: '95vw', boxShadow: '0 30px 60px rgba(0,0,0,0.3)', textAlign: 'center' }}>
            <div style={{ width: '64px', height: '64px', background: '#dcfce7', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 1.25rem', fontSize: '2rem' }}>
              ✅
            </div>
            <h2 style={{ margin: '0 0 0.5rem', fontSize: '1.4rem', color: '#166534', fontWeight: 900 }}>
              ¡Orden de Pedido a Finca Generada con Éxito!
            </h2>
            <p style={{ color: '#475569', fontSize: '0.9rem', marginBottom: '1.25rem' }}>
              {orderSuccessModal.message}
            </p>

            <div style={{ background: '#fef3c7', border: '2px solid #f59e0b', borderRadius: '12px', padding: '1.25rem', marginBottom: '1.5rem', textAlign: 'left' }}>
              <div style={{ fontWeight: 900, color: '#92400e', fontSize: '0.95rem', marginBottom: '0.35rem' }}>
                📢 NOTA OBLIGATORIA PARA LA FINCA:
              </div>
              <p style={{ margin: 0, fontSize: '0.9rem', color: '#78350f', fontWeight: 700, lineHeight: 1.4 }}>
                "{orderSuccessModal.notice}"
              </p>
            </div>

            <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'center', flexWrap: 'wrap' }}>
              <button
                onClick={() => {
                  if (orderSuccessModal.lineIds.length > 0) {
                    window.open(`/pedidos/print-labels/batch?ids=${orderSuccessModal.lineIds.join(',')}`, '_blank');
                  }
                }}
                style={{ padding: '0.85rem 1.8rem', borderRadius: '10px', border: 'none', background: '#1c5236', color: '#fff', fontWeight: 800, fontSize: '0.95rem', cursor: 'pointer', boxShadow: '0 4px 12px rgba(28,82,54,0.3)' }}
              >
                🖨️ Imprimir Etiquetas de Cajas (PDF)
              </button>
              <button
                onClick={() => setOrderSuccessModal(null)}
                style={{ padding: '0.85rem 1.5rem', borderRadius: '10px', border: '1px solid #cbd5e1', background: '#fff', color: '#475569', fontWeight: 700, cursor: 'pointer' }}
              >
                Cerrar
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── MODAL: EDITAR ORDEN / PRODUCTOS SIMULTÁNEOS ──────────────────────── */}
      {multiEditModal && multiEditModal.isOpen && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1100, padding: '1.5rem' }}>
          <div style={{ background: '#fff', borderRadius: '20px', padding: '2rem', width: '1200px', maxWidth: '96vw', maxHeight: '92vh', display: 'flex', flexDirection: 'column', boxShadow: '0 25px 60px rgba(0,0,0,0.35)' }}>
            
            {/* Modal Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '1.25rem', borderBottom: '1px solid #e2e8f0', paddingBottom: '1rem' }}>
              <div>
                <h2 style={{ margin: 0, fontSize: '1.35rem', color: '#1c5236', fontWeight: 900 }}>
                  ✏️ {multiEditModal.title}
                </h2>
                <p style={{ margin: '0.35rem 0 0', color: '#64748b', fontSize: '0.85rem' }}>
                  Edita simultáneamente producto, finca, precio unitario, fecha de salida, tipo de caja y cantidad.
                  Si reduces la cantidad, los excedentes se cancelan bajo política <b>FIFO</b> (las órdenes más recientes se liberan a estado NEW).
                </p>
              </div>
              <button
                type="button"
                onClick={() => setMultiEditModal(null)}
                style={{ background: 'none', border: 'none', fontSize: '1.5rem', cursor: 'pointer', color: '#94a3b8', lineHeight: 1 }}
              >
                ✕
              </button>
            </div>

            {/* Warning if any reduction is taking place */}
            {(() => {
              const totalCancelled = multiEditModal.items.reduce((sum, it) => sum + Math.max(0, it.orderedQty - (Number(it.newQty) || 0)), 0);
              if (totalCancelled > 0) {
                return (
                  <div style={{ background: '#fef2f2', border: '1px solid #fca5a5', borderRadius: '10px', padding: '0.85rem 1.25rem', marginBottom: '1.25rem', display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                    <span style={{ fontSize: '1.3rem' }}>⚠️</span>
                    <div style={{ fontSize: '0.85rem', color: '#991b1b', lineHeight: 1.4 }}>
                      <b>Atención:</b> Se cancelarán un total de <b>{totalCancelled} caja(s)</b>. Las órdenes de clientes con fecha de compra más reciente serán canceladas primero (FIFO), sus etiquetas quedarán invalidadas en la <b>Pestaña 5 (Etiquetas Canceladas)</b> y las líneas de cliente regresarán a estado <b>NEW</b> para ser asignadas nuevamente.
                    </div>
                  </div>
                );
              }
              return null;
            })()}

            {/* Modal Form */}
            <form onSubmit={handleSaveMultiEdit} style={{ display: 'flex', flexDirection: 'column', flex: 1, overflow: 'hidden' }}>
              
              {/* Table Container with scroll */}
              <div style={{ flex: 1, overflowY: 'auto', overflowX: 'auto', border: '1px solid #e2e8f0', borderRadius: '12px', marginBottom: '1.5rem' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.85rem' }}>
                  <thead>
                    <tr style={{ background: '#f8fafc', borderBottom: '2px solid #e2e8f0', color: '#475569', fontWeight: 800, fontSize: '0.75rem', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                      <th style={{ padding: '0.75rem 0.6rem', textAlign: 'center', width: '40px' }}>#</th>
                      <th style={{ padding: '0.75rem 0.8rem', minWidth: '180px' }}>Producto</th>
                      <th style={{ padding: '0.75rem 0.8rem', minWidth: '160px' }}>Finca Asignada</th>
                      <th style={{ padding: '0.75rem 0.8rem', width: '110px' }}>Precio Finca ($)</th>
                      <th style={{ padding: '0.75rem 0.8rem', width: '90px' }}>Box Type</th>
                      <th style={{ padding: '0.75rem 0.8rem', width: '135px' }}>Salida Finca</th>
                      <th style={{ padding: '0.75rem 0.8rem', minWidth: '140px' }}>Guía AWB</th>
                      <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center', width: '90px' }}>Cant. Actual</th>
                      <th style={{ padding: '0.75rem 0.8rem', textAlign: 'center', width: '115px' }}>Nueva Cantidad</th>
                    </tr>
                  </thead>
                  <tbody>
                    {multiEditModal.items.map((it, idx) => {
                      const isReduced = Number(it.newQty) < it.orderedQty;
                      const delta = it.orderedQty - Number(it.newQty);
                      return (
                        <tr key={it.id || idx} style={{ borderBottom: '1px solid #f1f5f9', background: idx % 2 === 0 ? '#fff' : '#fafafa' }}>
                          <td style={{ padding: '0.65rem 0.6rem', textAlign: 'center', color: '#94a3b8', fontWeight: 700 }}>
                            {idx + 1}
                          </td>
                          <td style={{ padding: '0.65rem 0.8rem' }}>
                            <select
                              value={it.productId || ''}
                              onChange={e => updateMultiEditItem(idx, 'productId', e.target.value)}
                              style={{ width: '100%', padding: '0.45rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.82rem', fontWeight: 600, color: '#1e293b' }}
                            >
                              <option value="">{it.productCode} - {it.productName}</option>
                              {products.map(p => (
                                <option key={p.id} value={p.id}>{p.code} - {p.name}</option>
                              ))}
                            </select>
                          </td>
                          <td style={{ padding: '0.65rem 0.8rem' }}>
                            <select
                              value={it.farmId || ''}
                              onChange={e => updateMultiEditItem(idx, 'farmId', e.target.value)}
                              style={{ width: '100%', padding: '0.45rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.82rem', fontWeight: 600, color: '#1e293b' }}
                            >
                              <option value="">— Sin cambiar finca —</option>
                              {farms.map(f => (
                                <option key={f.id} value={f.id}>{f.name}</option>
                              ))}
                            </select>
                          </td>
                          <td style={{ padding: '0.65rem 0.8rem' }}>
                            <input
                              type="number"
                              step="0.01"
                              min="0"
                              value={it.farmPrice}
                              onChange={e => updateMultiEditItem(idx, 'farmPrice', parseFloat(e.target.value) || 0)}
                              style={{ width: '100%', padding: '0.45rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.85rem', fontWeight: 700, color: '#166534', boxSizing: 'border-box' }}
                            />
                          </td>
                          <td style={{ padding: '0.65rem 0.8rem' }}>
                            <select
                              value={it.boxType || 'QB'}
                              onChange={e => updateMultiEditItem(idx, 'boxType', e.target.value)}
                              style={{ width: '100%', padding: '0.45rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.82rem', fontWeight: 700 }}
                            >
                              {(() => {
                                const opts = getFilteredBoxTypesForFarm(it.farmId, it.boxType);
                                const usfOpts = opts.filter(o => o.group.includes('USF'));
                                const farmOpts = opts.filter(o => o.group.includes('Finca'));
                                const otherOpts = opts.filter(o => o.group === 'Otras');
                                return (
                                  <>
                                    <optgroup label="📦 Cajas USF Estándar (3)">
                                      {usfOpts.map(o => (
                                        <option key={o.code} value={o.code}>{o.label}</option>
                                      ))}
                                    </optgroup>
                                    {farmOpts.length > 0 && (
                                      <optgroup label="🌻 Cajas de Finca (máx 3)">
                                        {farmOpts.map(o => (
                                          <option key={o.code} value={o.code}>{o.label}</option>
                                        ))}
                                      </optgroup>
                                    )}
                                    {otherOpts.length > 0 && (
                                      <optgroup label="Otras">
                                        {otherOpts.map(o => (
                                          <option key={o.code} value={o.code}>{o.label}</option>
                                        ))}
                                      </optgroup>
                                    )}
                                  </>
                                );
                              })()}
                            </select>
                          </td>
                          <td style={{ padding: '0.65rem 0.8rem' }}>
                            <input
                              type="date"
                              value={it.farmDepartureDate ? it.farmDepartureDate.split('T')[0] : ''}
                              onChange={e => updateMultiEditItem(idx, 'farmDepartureDate', e.target.value)}
                              style={{ width: '100%', padding: '0.45rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.8rem', boxSizing: 'border-box' }}
                            />
                          </td>
                          <td style={{ padding: '0.65rem 0.8rem' }}>
                            <input
                              placeholder="Ej. 729-12345678"
                              value={it.airwayBill || ''}
                              onChange={e => updateMultiEditItem(idx, 'airwayBill', e.target.value)}
                              style={{ width: '100%', padding: '0.45rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.82rem', boxSizing: 'border-box' }}
                            />
                          </td>
                          <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center' }}>
                            <span style={{ display: 'inline-block', padding: '0.3rem 0.7rem', background: '#f1f5f9', color: '#334155', borderRadius: '6px', fontWeight: 800, fontSize: '0.9rem' }}>
                              {it.orderedQty}
                            </span>
                          </td>
                          <td style={{ padding: '0.65rem 0.8rem', textAlign: 'center' }}>
                            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '0.2rem' }}>
                              <input
                                type="number"
                                min="0"
                                max={it.orderedQty}
                                value={it.newQty}
                                onChange={e => {
                                  const val = parseInt(e.target.value);
                                  updateMultiEditItem(idx, 'newQty', isNaN(val) ? 0 : Math.max(0, Math.min(it.orderedQty, val)));
                                }}
                                style={{
                                  width: '75px',
                                  padding: '0.45rem',
                                  border: isReduced ? '2px solid #ef4444' : '1px solid #cbd5e1',
                                  borderRadius: '6px',
                                  fontSize: '0.9rem',
                                  fontWeight: 800,
                                  textAlign: 'center',
                                  background: isReduced ? '#fef2f2' : '#fff',
                                  color: isReduced ? '#b91c1c' : '#1e293b',
                                  boxSizing: 'border-box'
                                }}
                              />
                              {isReduced && (
                                <span style={{ fontSize: '0.68rem', color: '#dc2626', fontWeight: 800, whiteSpace: 'nowrap' }}>
                                  -{delta} caja(s) FIFO
                                </span>
                              )}
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {/* Modal Footer */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '1rem' }}>
                <div style={{ fontSize: '0.85rem', color: '#64748b' }}>
                  Total de productos en edición: <b>{multiEditModal.items.length}</b> &nbsp;|&nbsp;
                  Total cajas actuales: <b>{multiEditModal.items.reduce((s, it) => s + (Number(it.newQty) || 0), 0)}</b>
                </div>
                <div style={{ display: 'flex', gap: '0.75rem' }}>
                  <button
                    type="button"
                    onClick={() => setMultiEditModal(null)}
                    style={{ padding: '0.65rem 1.4rem', borderRadius: '8px', border: '1px solid #cbd5e1', background: '#fff', color: '#475569', fontWeight: 700, cursor: 'pointer', fontSize: '0.9rem' }}
                  >
                    Cancelar
                  </button>
                  <button
                    type="submit"
                    disabled={savingLineAction}
                    style={{ padding: '0.65rem 1.6rem', borderRadius: '8px', border: 'none', background: 'linear-gradient(135deg, #1c5236, #2d6a4f)', color: '#fff', fontWeight: 800, cursor: 'pointer', fontSize: '0.9rem', boxShadow: '0 4px 12px rgba(28,82,54,0.3)' }}
                  >
                    {savingLineAction ? 'Guardando...' : '💾 Guardar Cambios'}
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ── MODAL: REPORTE CONSOLIDADO GUÍA AÉREA MASTER (Excel/PDF) ─────── */}
      {selectedAwbForReport && (
        <MasterAwbReportModal
          awb={selectedAwbForReport.awb}
          agency={selectedAwbForReport.agency}
          onClose={() => setSelectedAwbForReport(null)}
        />
      )}
    </MainLayout>
  );
}
