'use client';

import React, { useState, useEffect, useMemo, useRef } from 'react';
import MainLayout from '@/components/layout/MainLayout';
import { formatDateToYYYYMMDD } from '@/lib/dateUtils';
import CameraBarcodeScannerModal from '@/components/cold-room/CameraBarcodeScannerModal';
import MasterAwbReportModal from '@/components/reports/MasterAwbReportModal';

type ColdRoomItem = {
  id: string;
  orderId: string;
  po: string;
  orderNumber: string;
  finca: string;
  farmId?: string | null;
  farmRuc?: string;
  item: string;
  prodDesc: string;
  qty: number;
  boxType: string;
  precioCaja: number;
  precioTotal: number;
  salidaFinca: string;
  shipdate: string;
  deliver: string;
  agencia: string;
  awb: string;
  master: string;
  orderDate?: string;
  fechaPedido: string;
  hawb: string;
  boxNumber: string;
  uniqueCode: string;
  tracking: string;
  consolidado: string;
  status: string;
  customerName?: string;
};

type AirwayBill = {
  id: string;
  agency: string;
  deliverDate: string;
  shipDate: string;
  awb: string;
  master: string;
};

export default function ColdRoomPage() {
  const [items, setItems] = useState<ColdRoomItem[]>([]);
  const [guias, setGuias] = useState<AirwayBill[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [lastSyncTime, setLastSyncTime] = useState<string>('');

  // Search & Filter state
  const [filterAwb, setFilterAwb] = useState('');
  const [filterMaster, setFilterMaster] = useState('');
  const [filterAgency, setFilterAgency] = useState('');
  const [filterDate, setFilterDate] = useState('');
  const [searchTerm, setSearchTerm] = useState('');

  // Ref to always hold current filters for silent background polling
  const filtersRef = useRef({ filterAwb, filterMaster, filterAgency, filterDate, searchTerm });
  useEffect(() => {
    filtersRef.current = { filterAwb, filterMaster, filterAgency, filterDate, searchTerm };
  }, [filterAwb, filterMaster, filterAgency, filterDate, searchTerm]);

  // Ref to store fingerprint of last fetched cold room items to detect actual changes
  const lastItemsSignatureRef = useRef<string>('');

  // Selected box lines
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  // Quick scanner input
  const [scannerCode, setScannerCode] = useState('');
  const [scanMessage, setScanMessage] = useState<{ text: string; isError: boolean } | null>(null);

  // Modals
  const [rejectModalOpen, setRejectModalOpen] = useState(false);
  const [rejectReason, setRejectReason] = useState('Flor marchita / Daño en frío');
  const [rejectPhotoUrl, setRejectPhotoUrl] = useState('');
  const [rejecting, setRejecting] = useState(false);

  const [changeAwbModalOpen, setChangeAwbModalOpen] = useState(false);
  const [newAwbVal, setNewAwbVal] = useState('');
  const [changingAwb, setChangingAwb] = useState(false);

  // Camera & Report modals & Responsive layout
  const [cameraModalOpen, setCameraModalOpen] = useState(false);
  const [selectedAwbForReport, setSelectedAwbForReport] = useState<{ awb: string; agency?: string } | null>(null);
  const [viewLayout, setViewLayout] = useState<'TABLE' | 'CARDS'>('TABLE');

  // Navigation Tabs & Sub-views (WhatsApp Points 9 & 10)
  const [activeTab, setActiveTab] = useState<'INVENTORY' | 'REJECTIONS' | 'CANCELLED'>('INVENTORY');
  const [rejectComment, setRejectComment] = useState('');
  const [rejections, setRejections] = useState<any[]>([]);
  const [loadingRejections, setLoadingRejections] = useState(false);
  const [searchRejections, setSearchRejections] = useState('');
  const [cancelledLabels, setCancelledLabels] = useState<any[]>([]);
  const [loadingCancelled, setLoadingCancelled] = useState(false);
  const [searchCancelled, setSearchCancelled] = useState('');
  const [previewPhoto, setPreviewPhoto] = useState<string | null>(null);

  const fetchRejections = async () => {
    setLoadingRejections(true);
    try {
      const res = await fetch('/api/pedidos/rejections');
      if (res.ok) {
        const data = await res.json();
        setRejections(Array.isArray(data) ? data : []);
      }
    } catch (e) {
      console.error('Error fetching rejections:', e);
    } finally {
      setLoadingRejections(false);
    }
  };

  const fetchCancelled = async () => {
    setLoadingCancelled(true);
    try {
      const res = await fetch('/api/pedidos/cancelled-labels');
      if (res.ok) {
        const data = await res.json();
        setCancelledLabels(data.cancelledLabels || []);
      }
    } catch (e) {
      console.error('Error fetching cancelled labels:', e);
    } finally {
      setLoadingCancelled(false);
    }
  };

  // Fetch cold room items with silent refresh & change detection support
  const fetchItems = async (mode: 'initial' | 'manual' | 'background' | boolean = 'manual') => {
    const isBg = mode === 'background';
    const isInitial = mode === 'initial' || mode === true;
    const isManual = mode === 'manual' || mode === false;

    if (isInitial) setLoading(true);
    else if (isManual) setRefreshing(true);
    // mode === 'background' is completely silent (no loading spinner, no refreshing spinner)

    try {
      const q = new URLSearchParams();
      const current = filtersRef.current;
      if (current.filterAwb.trim()) q.set('awb', current.filterAwb.trim());
      if (current.filterMaster.trim()) q.set('master', current.filterMaster.trim());
      if (current.filterAgency.trim()) q.set('agency', current.filterAgency.trim());
      if (current.filterDate.trim()) q.set('date', current.filterDate.trim());
      if (current.searchTerm.trim()) q.set('search', current.searchTerm.trim());

      const [resItems, resGuias] = await Promise.all([
        fetch(`/api/cold-room?${q.toString()}`),
        fetch('/api/guias')
      ]);

      if (resItems.ok) {
        const newItems = await resItems.json();
        const signature = JSON.stringify(newItems);
        // Only update state if real change is detected or if initial/manual
        if (!isBg || signature !== lastItemsSignatureRef.current) {
          lastItemsSignatureRef.current = signature;
          setItems(newItems || []);
          setLastSyncTime(new Date().toLocaleTimeString('es-EC'));
        }
      }

      if (resGuias.ok && !isBg) {
        setGuias(await resGuias.json());
      }
    } catch (err) {
      console.error('Error fetching cold room data:', err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchItems('initial');

    // Polling en segundo plano cada 30 segundos (silencioso, solo actualiza si hay cambios reales)
    const interval = setInterval(() => {
      fetchItems('background');
    }, 30000);

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

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

  const handleClearFilters = () => {
    setFilterAwb('');
    setFilterMaster('');
    setFilterAgency('');
    setFilterDate('');
    setSearchTerm('');
    filtersRef.current = { filterAwb: '', filterMaster: '', filterAgency: '', filterDate: '', searchTerm: '' };
    setTimeout(() => {
      fetchItems('manual');
    }, 20);
  };

  // Selection handlers
  const toggleSelectAll = () => {
    if (selectedIds.size === items.length) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(items.map(i => i.id)));
    }
  };

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

  // Quick Barcode Scanning for Receiving in Cold Room
  const handleScanReceive = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!scannerCode.trim()) return;

    try {
      const res = await fetch('/api/cold-room', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'SCAN_RECEIVE', code: scannerCode.trim() })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al pistolear caja');

      setScanMessage({ text: `✅ ${data.message}`, isError: false });
      setScannerCode('');
      fetchItems();
    } catch (err: any) {
      setScanMessage({ text: `❌ ${err.message}`, isError: true });
    }
  };

  // Handle REJECT QC Submit
  const handleRejectQc = async () => {
    if (selectedIds.size === 0) {
      alert('Por favor selecciona al menos una caja para rechazar.');
      return;
    }
    if (!rejectReason.trim()) {
      alert('Por favor ingresa el motivo del rechazo.');
      return;
    }

    setRejecting(true);
    try {
      const res = await fetch('/api/cold-room', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'REJECT_QC',
          lineIds: Array.from(selectedIds),
          reason: rejectReason.trim(),
          comment: rejectComment.trim() || null,
          photoUrl: rejectPhotoUrl.trim() || null
        })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al procesar rechazo QC');

      alert(`✅ ${data.message}`);
      setRejectModalOpen(false);
      setSelectedIds(new Set());
      setRejectReason('Flor marchita / Daño en frío');
      setRejectComment('');
      setRejectPhotoUrl('');
      fetchItems();
      if (activeTab === 'REJECTIONS') fetchRejections();
    } catch (err: any) {
      alert(`Error: ${err.message}`);
    } finally {
      setRejecting(false);
    }
  };

  // Handle CHANGE AWB Submit
  const handleChangeAwb = async () => {
    if (selectedIds.size === 0) {
      alert('Por favor selecciona las cajas a las que deseas cambiar la AWB.');
      return;
    }
    if (!newAwbVal.trim()) {
      alert('Por favor ingresa la nueva AWB.');
      return;
    }

    setChangingAwb(true);
    try {
      const res = await fetch('/api/cold-room', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'CHANGE_AWB',
          lineIds: Array.from(selectedIds),
          newAwb: newAwbVal.trim()
        })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Error al cambiar AWB');

      alert(`✅ ${data.message}`);
      setChangeAwbModalOpen(false);
      setSelectedIds(new Set());
      setNewAwbVal('');
      fetchItems();
    } catch (err: any) {
      alert(`Error: ${err.message}`);
    } finally {
      setChangingAwb(false);
    }
  };

  // Status badge helper
  const getStatusBadge = (s: string) => {
    switch (s) {
      case 'SHIPPED':
        return <span style={{ background: '#dcfce7', color: '#166534', padding: '0.2rem 0.6rem', borderRadius: '10px', fontWeight: 800, fontSize: '0.72rem' }}>SHIPPED</span>;
      case 'RECEIVED':
        return <span style={{ background: '#dbeafe', color: '#1e40af', padding: '0.2rem 0.6rem', borderRadius: '10px', fontWeight: 800, fontSize: '0.72rem' }}>RECEIVED</span>;
      case 'FARM ASIGNED':
      case 'CONFIRMED':
        return <span style={{ background: '#fef08a', color: '#854d0e', padding: '0.2rem 0.6rem', borderRadius: '10px', fontWeight: 800, fontSize: '0.72rem' }}>FARM ASIGNED</span>;
      default:
        return <span style={{ background: '#f3f4f6', color: '#374151', padding: '0.2rem 0.6rem', borderRadius: '10px', fontWeight: 700, fontSize: '0.72rem' }}>{s}</span>;
    }
  };

  const selectedItemsList = useMemo(() => {
    return items.filter(i => selectedIds.has(i.id));
  }, [items, selectedIds]);

  const filteredRejections = useMemo(() => {
    if (!searchRejections.trim()) return rejections;
    const q = searchRejections.toLowerCase();
    return rejections.filter((r: any) =>
      (r.boxNumber || '').toLowerCase().includes(q) ||
      (r.productCode || '').toLowerCase().includes(q) ||
      (r.productName || '').toLowerCase().includes(q) ||
      (r.farm?.name || '').toLowerCase().includes(q) ||
      (r.reason || '').toLowerCase().includes(q) ||
      (r.comment || '').toLowerCase().includes(q)
    );
  }, [rejections, searchRejections]);

  const filteredCancelled = useMemo(() => {
    if (!searchCancelled.trim()) return cancelledLabels;
    const q = searchCancelled.toLowerCase();
    return cancelledLabels.filter((c: any) =>
      (c.uniqueCode || '').toLowerCase().includes(q) ||
      (c.boxNumber || '').toLowerCase().includes(q) ||
      (c.itemCode || '').toLowerCase().includes(q) ||
      (c.productName || '').toLowerCase().includes(q) ||
      (c.farmName || '').toLowerCase().includes(q) ||
      (c.customerName || '').toLowerCase().includes(q) ||
      (c.po || '').toLowerCase().includes(q) ||
      (c.reason || '').toLowerCase().includes(q)
    );
  }, [cancelledLabels, searchCancelled]);

  return (
    <MainLayout>
      <div style={{ padding: '1.5rem', maxWidth: '1600px', margin: '0 auto' }}>
        {/* 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: '#1e3a8a' }}>
              ❄️ Módulo Cuarto Frío (Recepción, QC & Despacho)
            </h1>
            <p style={{ margin: '0.25rem 0 0', color: '#666', fontSize: '0.88rem' }}>
              ESTO PROVIENE DEL MÓDULO DE PEDIDO A FINCAS · Control de calidad, rechazo QC, cambio de AWB y confirmación de ingreso.
            </p>
          </div>

          {/* Action Buttons as in Image 4 */}
          <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap', alignItems: 'center' }}>
            <button
              type="button"
              onClick={() => fetchItems(false)}
              disabled={refreshing}
              style={{
                padding: '0.7rem 1.25rem',
                borderRadius: '8px',
                border: '1px solid #cbd5e1',
                background: '#fff',
                color: '#1e293b',
                fontWeight: 800,
                fontSize: '0.9rem',
                cursor: refreshing ? 'not-allowed' : 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '0.45rem',
                boxShadow: '0 2px 6px rgba(0,0,0,0.06)'
              }}
              title="Actualizar la tabla de frío 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>

            <button
              type="button"
              onClick={() => setCameraModalOpen(true)}
              style={{
                padding: '0.7rem 1.4rem',
                borderRadius: '8px',
                border: 'none',
                background: 'linear-gradient(135deg, #10b981, #059669)',
                color: '#fff',
                fontWeight: 900,
                fontSize: '0.92rem',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '0.4rem',
                boxShadow: '0 4px 12px rgba(16, 185, 129, 0.35)'
              }}
              title="Abrir cámara para escanear etiquetas"
            >
              📷 ESCANEAR CÁMARA
            </button>

            {filterAwb.trim() && (
              <button
                type="button"
                onClick={() => setSelectedAwbForReport({ awb: filterAwb.trim(), agency: filterAgency })}
                style={{
                  padding: '0.7rem 1.4rem',
                  borderRadius: '8px',
                  border: 'none',
                  background: '#8b5cf6',
                  color: '#fff',
                  fontWeight: 900,
                  fontSize: '0.92rem',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.4rem',
                  boxShadow: '0 4px 12px rgba(139, 92, 246, 0.35)'
                }}
                title="Ver reporte master de la guía filtrada"
              >
                📋 REPORTE GUÍA AWB
              </button>
            )}

            <button
              onClick={() => {
                if (selectedIds.size === 0) {
                  alert('Selecciona una o más cajas de la tabla para rechazar.');
                  return;
                }
                setRejectModalOpen(true);
              }}
              style={{
                padding: '0.7rem 1.6rem',
                borderRadius: '8px',
                border: 'none',
                background: '#0284c7', // Bright Blue as in image 4
                color: '#fff',
                fontWeight: 900,
                fontSize: '0.92rem',
                letterSpacing: '0.04em',
                cursor: 'pointer',
                boxShadow: '0 4px 12px rgba(2,132,199,0.35)'
              }}
            >
              🛡️ REJECT QC ({selectedIds.size})
            </button>

            <button
              onClick={() => {
                if (selectedIds.size === 0) {
                  alert('Selecciona una o más cajas de la tabla para cambiar la AWB.');
                  return;
                }
                setChangeAwbModalOpen(true);
              }}
              style={{
                padding: '0.7rem 1.6rem',
                borderRadius: '8px',
                border: 'none',
                background: '#eab308', // Yellow as in image 4
                color: '#78350f',
                fontWeight: 900,
                fontSize: '0.92rem',
                letterSpacing: '0.04em',
                cursor: 'pointer',
                boxShadow: '0 4px 12px rgba(234,179,8,0.35)'
              }}
            >
              ✈️ CHANGE AWB ({selectedIds.size})
            </button>
          </div>
        </div>

        {/* ── NAVEGACIÓN POR PESTAÑAS (CUARTO FRÍO, RECHAZOS QC, ETIQUETAS CANCELADAS) ── */}
        <div style={{ display: 'flex', gap: '0.5rem', borderBottom: '2px solid #e2e8f0', marginBottom: '1.25rem', paddingBottom: '0.25rem', flexWrap: 'wrap' }}>
          <button
            type="button"
            onClick={() => setActiveTab('INVENTORY')}
            style={{
              padding: '0.65rem 1.25rem',
              borderRadius: '8px',
              border: 'none',
              background: activeTab === 'INVENTORY' ? '#1e3a8a' : '#f1f5f9',
              color: activeTab === 'INVENTORY' ? '#fff' : '#475569',
              fontWeight: 800,
              fontSize: '0.9rem',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '0.4rem',
              boxShadow: activeTab === 'INVENTORY' ? '0 4px 10px rgba(30, 58, 138, 0.25)' : 'none',
              transition: 'all 0.15s ease'
            }}
          >
            📦 Control y Recepción ({items.length})
          </button>

          <button
            type="button"
            onClick={() => {
              setActiveTab('REJECTIONS');
              fetchRejections();
            }}
            style={{
              padding: '0.65rem 1.25rem',
              borderRadius: '8px',
              border: 'none',
              background: activeTab === 'REJECTIONS' ? '#dc2626' : '#f1f5f9',
              color: activeTab === 'REJECTIONS' ? '#fff' : '#dc2626',
              fontWeight: 800,
              fontSize: '0.9rem',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '0.4rem',
              boxShadow: activeTab === 'REJECTIONS' ? '0 4px 10px rgba(220, 38, 38, 0.25)' : 'none',
              transition: 'all 0.15s ease'
            }}
          >
            🛡️ Rechazos QC y Ajustes {rejections.length > 0 ? `(${rejections.length})` : ''}
          </button>

          <button
            type="button"
            onClick={() => {
              setActiveTab('CANCELLED');
              fetchCancelled();
            }}
            style={{
              padding: '0.65rem 1.25rem',
              borderRadius: '8px',
              border: 'none',
              background: activeTab === 'CANCELLED' ? '#7f1d1d' : '#f1f5f9',
              color: activeTab === 'CANCELLED' ? '#fff' : '#7f1d1d',
              fontWeight: 800,
              fontSize: '0.9rem',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '0.4rem',
              boxShadow: activeTab === 'CANCELLED' ? '0 4px 10px rgba(127, 29, 29, 0.25)' : 'none',
              transition: 'all 0.15s ease'
            }}
          >
            🚫 Etiquetas Canceladas {cancelledLabels.length > 0 ? `(${cancelledLabels.length})` : ''}
          </button>
        </div>

        {activeTab === 'INVENTORY' && (
          <>
            {/* ── FILTROS DE BUSQUEDA SUPERIORES (Image 4) ─────────────────────── */}
            <div style={{ background: '#fff', borderRadius: '12px', padding: '1.25rem', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', marginBottom: '1.25rem', border: '1px solid #e2e8f0' }}>
          <div style={{ fontSize: '0.85rem', fontWeight: 800, color: '#1e3a8a', textTransform: 'uppercase', marginBottom: '0.75rem', letterSpacing: '0.04em', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
            <span style={{ background: '#22c55e', color: '#fff', padding: '0.15rem 0.5rem', borderRadius: '4px', fontSize: '0.75rem' }}>
              FILTROS DE BÚSQUEDA
            </span>
            <span>X GUÍA AÉREA, X MASTER, X AGENCIA DE CARGA, MÓDULO FECHA</span>
          </div>

          <form onSubmit={handleFilterSubmit}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '0.75rem', marginBottom: '0.75rem' }}>
              <div>
                <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.25rem' }}>
                  Guía Aérea (AWB)
                </label>
                <input
                  value={filterAwb}
                  onChange={e => setFilterAwb(e.target.value)}
                  placeholder="Ej. 729-40451234"
                  style={{ width: '100%', padding: '0.5rem 0.7rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.85rem', fontWeight: 700, fontFamily: 'monospace', boxSizing: 'border-box' }}
                />
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.25rem' }}>
                  Master (4 Dígitos)
                </label>
                <input
                  value={filterMaster}
                  onChange={e => setFilterMaster(e.target.value)}
                  placeholder="Ej. 1234"
                  style={{ width: '100%', padding: '0.5rem 0.7rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.85rem', fontWeight: 700, fontFamily: 'monospace', boxSizing: 'border-box' }}
                />
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.25rem' }}>
                  Agencia de Carga
                </label>
                <select
                  value={filterAgency}
                  onChange={e => setFilterAgency(e.target.value)}
                  style={{ width: '100%', padding: '0.5rem 0.7rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.85rem', fontWeight: 600, boxSizing: 'border-box' }}
                >
                  <option value="">— Todas las agencias —</option>
                  <option value="FEDEX">FEDEX</option>
                  <option value="FLOWERCARGO">FLOWERCARGO</option>
                  <option value="CHAMPION">CHAMPION</option>
                  <option value="LATAM">LATAM CARGO</option>
                  <option value="AVIANCA">AVIANCA</option>
                </select>
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.25rem' }}>
                  Módulo Fecha (Salida/Vuelo/Entrega)
                </label>
                <input
                  type="date"
                  value={filterDate}
                  onChange={e => setFilterDate(e.target.value)}
                  style={{ width: '100%', padding: '0.45rem 0.6rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.85rem', boxSizing: 'border-box' }}
                />
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.25rem' }}>
                  Búsqueda Libre
                </label>
                <input
                  value={searchTerm}
                  onChange={e => setSearchTerm(e.target.value)}
                  placeholder="Finca, Item, BOX#, Tracking..."
                  style={{ width: '100%', padding: '0.5rem 0.7rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.85rem', boxSizing: 'border-box' }}
                />
              </div>
            </div>

            <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
              <button
                type="button"
                onClick={handleClearFilters}
                style={{ padding: '0.45rem 1rem', borderRadius: '6px', border: '1px solid #cbd5e1', background: '#fff', cursor: 'pointer', fontSize: '0.82rem' }}
              >
                Limpiar Filtros
              </button>
              <button
                type="submit"
                style={{ padding: '0.45rem 1.4rem', borderRadius: '6px', border: 'none', background: '#1e3a8a', color: '#fff', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem' }}
              >
                🔍 Filtrar Cajas
              </button>
            </div>
          </form>
        </div>

        {/* ── BARRA DE PISTOLEO / ESCÁNER RÁPIDO Y CÁMARA ─────────────────── */}
        <div style={{ background: '#f8fafc', borderRadius: '12px', padding: '1rem 1.25rem', marginBottom: '1rem', border: '2px dashed #94a3b8', display: 'flex', alignItems: 'center', gap: '1rem', flexWrap: 'wrap' }}>
          <div style={{ fontSize: '1.6rem' }}>📟</div>
          <div style={{ flex: 1, minWidth: '220px' }}>
            <div style={{ fontSize: '0.9rem', fontWeight: 800, color: '#1e293b' }}>
              Recepción de Cajas: Pistola o Cámara Móvil / Tablet
            </div>
            <div style={{ fontSize: '0.75rem', color: '#64748b' }}>
              Pistolea el código de barra o usa la cámara de tu teléfono/tablet para escanear y marcar como RECIBIDO.
            </div>
          </div>

          <div style={{ display: 'flex', gap: '0.6rem', flexWrap: 'wrap', alignItems: 'center', flex: '1 1 360px' }}>
            <form onSubmit={handleScanReceive} style={{ display: 'flex', gap: '0.4rem', flex: 1, minWidth: '240px' }}>
              <input
                value={scannerCode}
                onChange={e => setScannerCode(e.target.value)}
                placeholder="Pistolear aquí..."
                autoFocus
                style={{ flex: 1, padding: '0.6rem 0.8rem', border: '2px solid #0284c7', borderRadius: '8px', fontSize: '0.92rem', fontWeight: 700, fontFamily: 'monospace' }}
              />
              <button
                type="submit"
                style={{ padding: '0.6rem 1.1rem', borderRadius: '8px', border: 'none', background: '#0284c7', color: '#fff', fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap' }}
              >
                📥 Recibir
              </button>
            </form>

            <button
              type="button"
              onClick={() => setCameraModalOpen(true)}
              style={{
                padding: '0.6rem 1.25rem',
                borderRadius: '8px',
                border: 'none',
                background: 'linear-gradient(135deg, #10b981, #059669)',
                color: '#fff',
                fontWeight: 800,
                fontSize: '0.88rem',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '0.4rem',
                boxShadow: '0 4px 12px rgba(16, 185, 129, 0.35)',
                whiteSpace: 'nowrap'
              }}
              title="Abrir cámara del teléfono o tablet para escanear código de barras"
            >
              📷 Escanear con Cámara
            </button>

            <button
              type="button"
              onClick={() => fetchItems(false)}
              disabled={refreshing}
              style={{
                padding: '0.6rem 1rem',
                borderRadius: '8px',
                border: '1px solid #cbd5e1',
                background: '#fff',
                color: '#334155',
                fontWeight: 700,
                fontSize: '0.85rem',
                cursor: refreshing ? 'not-allowed' : 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '0.35rem',
                whiteSpace: 'nowrap'
              }}
              title="Refrescar datos de pistoleo inmediatamente"
            >
              🔄 {refreshing ? 'Sincronizando...' : 'Refrescar'}
            </button>
          </div>
        </div>

        {scanMessage && (
          <div style={{ padding: '0.75rem 1rem', borderRadius: '8px', marginBottom: '1rem', background: scanMessage.isError ? '#fee2e2' : '#dcfce7', color: scanMessage.isError ? '#991b1b' : '#166534', fontWeight: 700, fontSize: '0.88rem' }}>
            {scanMessage.text}
          </div>
        )}

        {/* Layout Switcher & Status Bar (Optimized for Mobile/Tablet) */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem', flexWrap: 'wrap', gap: '0.75rem' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
            <span style={{ fontSize: '0.85rem', fontWeight: 700, color: '#334155' }}>
              {items.length} cajas en Cuarto Frío
            </span>
            {selectedIds.size > 0 && (
              <span style={{ background: '#dcfce7', color: '#166534', padding: '0.2rem 0.6rem', borderRadius: '12px', fontSize: '0.78rem', fontWeight: 800 }}>
                {selectedIds.size} seleccionadas
              </span>
            )}
            {lastSyncTime && (
              <span style={{ fontSize: '0.75rem', color: '#64748b', background: '#f1f5f9', padding: '0.15rem 0.5rem', borderRadius: '6px' }}>
                🕒 Sincronizado: <b>{lastSyncTime}</b>
              </span>
            )}
          </div>

          <div style={{ display: 'flex', background: '#e2e8f0', padding: '0.25rem', borderRadius: '8px', gap: '0.25rem' }}>
            <button
              type="button"
              onClick={() => setViewLayout('TABLE')}
              style={{
                padding: '0.4rem 0.85rem',
                borderRadius: '6px',
                border: 'none',
                background: viewLayout === 'TABLE' ? '#1e3a8a' : 'transparent',
                color: viewLayout === 'TABLE' ? '#fff' : '#475569',
                fontWeight: 700,
                fontSize: '0.8rem',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '0.35rem'
              }}
            >
              📊 Vista Tabla
            </button>
            <button
              type="button"
              onClick={() => setViewLayout('CARDS')}
              style={{
                padding: '0.4rem 0.85rem',
                borderRadius: '6px',
                border: 'none',
                background: viewLayout === 'CARDS' ? '#1e3a8a' : 'transparent',
                color: viewLayout === 'CARDS' ? '#fff' : '#475569',
                fontWeight: 700,
                fontSize: '0.8rem',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                gap: '0.35rem'
              }}
            >
              📱 Vista Móvil / Tarjetas
            </button>
          </div>
        </div>

        {/* ── VISTA TARJETAS MÓVIL / TABLET ───────────────────────────────── */}
        {viewLayout === 'CARDS' ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: '1rem', marginBottom: '1.5rem' }}>
            {items.length === 0 ? (
              <div style={{ gridColumn: '1 / -1', background: '#fff', borderRadius: '12px', padding: '3rem', textAlign: 'center', color: '#999', border: '1px solid #e2e8f0' }}>
                No hay cajas en el Cuarto Frío que coincidan con los filtros.
              </div>
            ) : (
              items.map(row => {
                const isSelected = selectedIds.has(row.id);
                const isReceived = row.status === 'RECEIVED';
                return (
                  <div
                    key={row.id}
                    style={{
                      background: isSelected ? '#f0fdf4' : '#fff',
                      border: isSelected ? '2px solid #22c55e' : '1px solid #e2e8f0',
                      borderRadius: '12px',
                      padding: '1rem',
                      boxShadow: '0 2px 6px rgba(0,0,0,0.04)',
                      display: 'flex',
                      flexDirection: 'column',
                      gap: '0.65rem'
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer' }}>
                        <input
                          type="checkbox"
                          checked={isSelected}
                          onChange={() => toggleSelectOne(row.id)}
                          style={{ width: '18px', height: '18px', cursor: 'pointer' }}
                        />
                        <span style={{ fontFamily: 'monospace', fontWeight: 900, fontSize: '1.05rem', color: '#0369a1', background: '#e0f2fe', padding: '0.2rem 0.5rem', borderRadius: '6px' }}>
                          #{row.boxNumber || '—'}
                        </span>
                        <span style={{ fontSize: '0.78rem', color: '#64748b', fontWeight: 700 }}>
                          ({row.boxType})
                        </span>
                      </label>

                      <div>
                        {getStatusBadge(row.status)}
                      </div>
                    </div>

                    <div>
                      <div style={{ fontSize: '0.95rem', fontWeight: 800, color: '#1e293b' }}>
                        {row.finca}
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', marginTop: '0.2rem' }}>
                        <span style={{ fontFamily: 'monospace', fontWeight: 800, color: '#dc2626', fontSize: '0.85rem' }}>
                          {row.item}
                        </span>
                        <span style={{ color: '#475569', fontSize: '0.82rem', fontWeight: 600 }}>
                          {row.prodDesc}
                        </span>
                      </div>
                    </div>

                    <div style={{ background: '#f8fafc', padding: '0.5rem 0.75rem', borderRadius: '8px', fontSize: '0.78rem', display: 'flex', flexDirection: 'column', gap: '0.25rem' }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ color: '#64748b' }}>Código Único:</span>
                        <span style={{ fontFamily: 'monospace', fontWeight: 700, color: '#1e3a8a' }}>{row.uniqueCode}</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ color: '#64748b' }}>AWB / Agencia:</span>
                        <span style={{ fontWeight: 700, color: '#0f766e' }}>{row.agencia} · {row.awb || '—'}</span>
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <span style={{ color: '#64748b' }}>Fechas:</span>
                        <span style={{ fontFamily: 'monospace', fontSize: '0.75rem' }}>Sal: {row.salidaFinca || '—'} | Ent: {row.deliver || '—'}</span>
                      </div>
                    </div>

                    <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.25rem' }}>
                      {!isReceived && (
                        <button
                          type="button"
                          onClick={async () => {
                            try {
                              const res = await fetch('/api/cold-room', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({ action: 'SCAN_RECEIVE', code: row.uniqueCode || row.boxNumber })
                              });
                              const d = await res.json();
                              if (res.ok) {
                                setScanMessage({ text: `✅ Caja #${row.boxNumber} recibida en frío`, isError: false });
                                fetchItems();
                              } else {
                                alert(d.error || 'Error al recibir caja');
                              }
                            } catch (e: any) {
                              alert(e.message);
                            }
                          }}
                          style={{
                            flex: 1,
                            padding: '0.55rem',
                            borderRadius: '8px',
                            border: 'none',
                            background: '#10b981',
                            color: '#fff',
                            fontWeight: 800,
                            fontSize: '0.82rem',
                            cursor: 'pointer',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            gap: '0.35rem'
                          }}
                        >
                          📥 Marcar Recibido
                        </button>
                      )}

                      <button
                        type="button"
                        onClick={() => window.open(`/pedidos/print-labels/${row.id}`, '_blank')}
                        style={{
                          padding: '0.55rem 0.9rem',
                          borderRadius: '8px',
                          border: '1px solid #cbd5e1',
                          background: '#fff',
                          color: '#1c5236',
                          fontWeight: 700,
                          fontSize: '0.82rem',
                          cursor: 'pointer',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '0.35rem'
                        }}
                      >
                        🖨️ Etiqueta
                      </button>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        ) : (
          /* ── TABLA PRINCIPAL DE CUARTO FRÍO (Image 4) ────────────────────── */
          <div style={{ background: '#fff', borderRadius: '12px', boxShadow: '0 4px 14px rgba(0,0,0,0.06)', overflowX: 'auto', border: '1px solid #e2e8f0', marginBottom: '1rem' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.8rem', textAlign: 'left', minWidth: '1500px' }}>
              <thead>
                <tr style={{ background: '#f8fafc', borderBottom: '2px solid #cbd5e1', color: '#334155' }}>
                  <th style={{ padding: '0.75rem 0.6rem', textAlign: 'center', width: '40px' }}>
                    <input
                      type="checkbox"
                      checked={items.length > 0 && selectedIds.size === items.length}
                      onChange={toggleSelectAll}
                      style={{ cursor: 'pointer' }}
                    />
                  </th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800 }}>FINCA</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, color: '#dc2626' }}>ITEM</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800 }}>ProdDesc</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center' }}>Qty</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center' }}>Box</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'right' }}>Precio Caja</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'right' }}>Precio Total</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center', background: '#fef08a' }}>SALIDA FINCA</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center', background: '#fef08a' }}>SHIPDATE</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center', background: '#fef08a' }}>DELIVER</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center' }}>AGENCIA</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800 }}>AWB</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center' }}>ORDER DATE</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center' }}>HAWB</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 900, textAlign: 'center', background: '#38bdf8', color: '#0c4a6e' }}>BOX#</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800 }}>Tracking</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center' }}>Estado</th>
                  <th style={{ padding: '0.75rem 0.6rem', fontWeight: 800, textAlign: 'center' }}>Acción</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={19} style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>
                      Cargando inventario de Cuarto Frío...
                    </td>
                  </tr>
                ) : items.length === 0 ? (
                  <tr>
                    <td colSpan={19} style={{ textAlign: 'center', padding: '3rem', color: '#999' }}>
                      No hay cajas en el Cuarto Frío que coincidan con los filtros.
                    </td>
                  </tr>
                ) : (
                  items.map((row, idx) => {
                    const isSelected = selectedIds.has(row.id);
                    return (
                      <tr
                        key={row.id}
                        style={{
                          borderBottom: '1px solid #f1f5f9',
                          background: isSelected ? '#f0fdf4' : idx % 2 === 0 ? '#fff' : '#f8fafc'
                        }}
                      >
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center' }}>
                          <input
                            type="checkbox"
                            checked={isSelected}
                            onChange={() => toggleSelectOne(row.id)}
                            style={{ cursor: 'pointer' }}
                          />
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', fontWeight: 800, color: '#1e293b' }}>
                          {row.finca}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', fontFamily: 'monospace', fontWeight: 900, color: '#dc2626' }}>
                          {row.item}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', fontWeight: 600, minWidth: '170px' }}>
                          {row.prodDesc}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center', fontWeight: 700 }}>
                          {row.qty}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center', fontWeight: 700, color: '#64748b' }}>
                          {row.boxType}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'right', fontWeight: 600 }}>
                          ${row.precioCaja.toFixed(2)}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'right', fontWeight: 800, color: '#1c5236' }}>
                          ${row.precioTotal.toFixed(2)}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center', fontFamily: 'monospace', background: '#fefce8' }}>
                          {row.salidaFinca || '—'}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center', fontFamily: 'monospace', background: '#fefce8' }}>
                          {row.shipdate || '—'}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 700, background: '#fefce8' }}>
                          {row.deliver || '—'}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center', fontWeight: 700, color: '#475569' }}>
                          {row.agencia}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', fontFamily: 'monospace', fontWeight: 800, color: '#1e3a8a' }}>
                          {row.awb || '—'}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center', fontFamily: 'monospace', fontSize: '0.78rem', color: '#1e293b', fontWeight: 600 }}>
                          {row.orderDate || row.fechaPedido || '—'}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center', fontFamily: 'monospace', color: '#64748b' }}>
                          {row.hawb}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 900, background: '#e0f2fe', color: '#0369a1', fontSize: '0.9rem' }}>
                          {row.boxNumber || '—'}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', fontFamily: 'monospace', color: row.tracking ? '#166534' : '#94a3b8', fontWeight: 600 }}>
                          {row.tracking || '—'}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center' }}>
                          {getStatusBadge(row.status)}
                        </td>
                        <td style={{ padding: '0.55rem 0.6rem', textAlign: 'center' }}>
                          <button
                            onClick={() => window.open(`/pedidos/print-labels/${row.id}`, '_blank')}
                            style={{ padding: '0.25rem 0.55rem', borderRadius: '4px', border: 'none', background: '#1c5236', color: '#fff', cursor: 'pointer', fontSize: '0.72rem', fontWeight: 700 }}
                          >
                            🖨️ Etiqueta
                          </button>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        )}

        <div style={{ marginTop: '0.75rem', color: '#64748b', fontSize: '0.8rem', display: 'flex', justifyContent: 'space-between' }}>
          <span>{items.length} cajas en Cuarto Frío</span>
          <span>{selectedIds.size} seleccionadas</span>
        </div>
      </>
    )}

  {/* ── SECCIÓN 2: RECHAZOS QC Y AJUSTES (Image 4 & WhatsApp Requirements) ── */}
  {activeTab === 'REJECTIONS' && (
    <div>
      <div style={{ background: '#fff', borderRadius: '12px', padding: '1.25rem', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', marginBottom: '1.25rem', border: '1px solid #e2e8f0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '1rem' }}>
        <div>
          <h2 style={{ margin: 0, fontSize: '1.25rem', color: '#991b1b', fontWeight: 900, display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
            🛡️ Registro de Rechazos por Control de Calidad (QC)
          </h2>
          <p style={{ margin: '0.25rem 0 0', color: '#64748b', fontSize: '0.85rem' }}>
            Historial de cajas rechazadas en frío, descuentos automáticos a fincas y emisión de etiquetas de devolución.
          </p>
        </div>

        <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
          <input
            type="text"
            placeholder="Buscar por caja, producto, motivo o finca..."
            value={searchRejections}
            onChange={e => setSearchRejections(e.target.value)}
            style={{ padding: '0.55rem 0.85rem', borderRadius: '6px', border: '1px solid #cbd5e1', fontSize: '0.85rem', minWidth: '280px' }}
          />
          <button
            type="button"
            onClick={fetchRejections}
            disabled={loadingRejections}
            style={{ padding: '0.55rem 1rem', borderRadius: '6px', border: '1px solid #cbd5e1', background: '#fff', fontWeight: 700, fontSize: '0.85rem', cursor: 'pointer' }}
          >
            {loadingRejections ? '...' : '🔄 Actualizar'}
          </button>
        </div>
      </div>

      {/* Rejections Table */}
      <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #e2e8f0', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.82rem' }}>
          <thead>
            <tr style={{ background: '#f8fafc', borderBottom: '2px solid #e2e8f0', color: '#334155' }}>
              <th style={{ padding: '0.75rem 1rem' }}>Fecha</th>
              <th style={{ padding: '0.75rem 1rem' }}>Caja (BOX#)</th>
              <th style={{ padding: '0.75rem 1rem' }}>Producto</th>
              <th style={{ padding: '0.75rem 1rem' }}>Finca</th>
              <th style={{ padding: '0.75rem 1rem' }}>Motivo Rechazo</th>
              <th style={{ padding: '0.75rem 1rem' }}>Comentario / Recomendación</th>
              <th style={{ padding: '0.75rem 1rem' }}>Precio Caja</th>
              <th style={{ padding: '0.75rem 1rem' }}>Foto</th>
              <th style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>Etiqueta Devolución</th>
            </tr>
          </thead>
          <tbody>
            {loadingRejections ? (
              <tr><td colSpan={9} style={{ textAlign: 'center', padding: '3rem', color: '#64748b' }}>Cargando rechazos...</td></tr>
            ) : filteredRejections.length === 0 ? (
              <tr><td colSpan={9} style={{ textAlign: 'center', padding: '3rem', color: '#64748b' }}>No hay registros de rechazos QC registrados.</td></tr>
            ) : (
              filteredRejections.map((rej: any) => (
                <tr key={rej.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                  <td style={{ padding: '0.75rem 1rem', whiteSpace: 'nowrap', color: '#64748b' }}>
                    {new Date(rej.createdAt).toLocaleString('es-EC')}
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 800, color: '#b91c1c' }}>
                    BOX#{rej.boxNumber || '—'}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    <span style={{ fontWeight: 700, color: '#1e3a8a' }}>{rej.productCode}</span>
                    <div style={{ fontSize: '0.75rem', color: '#475569' }}>{rej.productName}</div>
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 600 }}>
                    {rej.farm?.name || '—'}
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 700, color: '#dc2626' }}>
                    {rej.reason}
                  </td>
                  <td style={{ padding: '0.75rem 1rem', maxWidth: '240px', color: '#334155' }}>
                    {rej.comment || '—'}
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 700, color: '#047857' }}>
                    ${(rej.price || 0).toFixed(2)}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    {rej.photoUrl ? (
                      <button
                        type="button"
                        onClick={() => setPreviewPhoto(rej.photoUrl)}
                        style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}
                      >
                        <img src={rej.photoUrl} alt="Foto QC" style={{ width: '38px', height: '38px', objectFit: 'cover', borderRadius: '4px', border: '1px solid #cbd5e1' }} />
                      </button>
                    ) : (
                      <span style={{ color: '#94a3b8' }}>Sin foto</span>
                    )}
                  </td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>
                    <a
                      href={`/pedidos/print-labels/${rej.id}?type=qc`}
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '0.35rem',
                        padding: '0.35rem 0.85rem',
                        background: '#b91c1c',
                        color: '#fff',
                        borderRadius: '6px',
                        fontWeight: 700,
                        fontSize: '0.78rem',
                        textDecoration: 'none',
                        boxShadow: '0 2px 4px rgba(185, 28, 28, 0.25)'
                      }}
                    >
                      🖨️ Devolución
                    </a>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )}

  {/* ── SECCIÓN 3: ETIQUETAS CANCELADAS (WhatsApp Requirements) ── */}
  {activeTab === 'CANCELLED' && (
    <div>
      <div style={{ background: '#fff', borderRadius: '12px', padding: '1.25rem', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', marginBottom: '1.25rem', border: '1px solid #e2e8f0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '1rem' }}>
        <div>
          <h2 style={{ margin: 0, fontSize: '1.25rem', color: '#7f1d1d', fontWeight: 900, display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
            🚫 Etiquetas y Cajas Canceladas
          </h2>
          <p style={{ margin: '0.25rem 0 0', color: '#64748b', fontSize: '0.85rem' }}>
            Cajas anuladas o canceladas por ventas/administración. Códigos deshabilitados para evitar despachos indebidos.
          </p>
        </div>

        <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
          <input
            type="text"
            placeholder="Buscar por código único, caja, cliente o PO..."
            value={searchCancelled}
            onChange={e => setSearchCancelled(e.target.value)}
            style={{ padding: '0.55rem 0.85rem', borderRadius: '6px', border: '1px solid #cbd5e1', fontSize: '0.85rem', minWidth: '280px' }}
          />
          <button
            type="button"
            onClick={fetchCancelled}
            disabled={loadingCancelled}
            style={{ padding: '0.55rem 1rem', borderRadius: '6px', border: '1px solid #cbd5e1', background: '#fff', fontWeight: 700, fontSize: '0.85rem', cursor: 'pointer' }}
          >
            {loadingCancelled ? '...' : '🔄 Actualizar'}
          </button>
        </div>
      </div>

      {/* Cancelled Table */}
      <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #e2e8f0', boxShadow: '0 2px 8px rgba(0,0,0,0.06)', overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.82rem' }}>
          <thead>
            <tr style={{ background: '#f8fafc', borderBottom: '2px solid #e2e8f0', color: '#334155' }}>
              <th style={{ padding: '0.75rem 1rem' }}>Fecha Cancelación</th>
              <th style={{ padding: '0.75rem 1rem' }}>Código Único</th>
              <th style={{ padding: '0.75rem 1rem' }}>Caja</th>
              <th style={{ padding: '0.75rem 1rem' }}>Producto</th>
              <th style={{ padding: '0.75rem 1rem' }}>Finca</th>
              <th style={{ padding: '0.75rem 1rem' }}>Cliente / PO</th>
              <th style={{ padding: '0.75rem 1rem' }}>Motivo</th>
              <th style={{ padding: '0.75rem 1rem' }}>Estado</th>
              <th style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>Etiqueta</th>
            </tr>
          </thead>
          <tbody>
            {loadingCancelled ? (
              <tr><td colSpan={9} style={{ textAlign: 'center', padding: '3rem', color: '#64748b' }}>Cargando canceladas...</td></tr>
            ) : filteredCancelled.length === 0 ? (
              <tr><td colSpan={9} style={{ textAlign: 'center', padding: '3rem', color: '#64748b' }}>No hay etiquetas canceladas registradas.</td></tr>
            ) : (
              filteredCancelled.map((cl: any) => (
                <tr key={cl.id} style={{ borderBottom: '1px solid #f1f5f9', background: '#fff5f5' }}>
                  <td style={{ padding: '0.75rem 1rem', whiteSpace: 'nowrap', color: '#991b1b' }}>
                    {new Date(cl.cancelledAt).toLocaleString('es-EC')}
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontFamily: 'monospace', fontWeight: 700, color: '#dc2626' }}>
                    {cl.uniqueCode}
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 800, color: '#991b1b' }}>
                    BOX#{cl.boxNumber}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    <span style={{ fontWeight: 700 }}>{cl.itemCode}</span>
                    <div style={{ fontSize: '0.75rem', color: '#64748b' }}>{cl.productName}</div>
                  </td>
                  <td style={{ padding: '0.75rem 1rem', fontWeight: 600 }}>
                    {cl.farmName || '—'}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    <span style={{ fontWeight: 700 }}>PO#{cl.po || '—'}</span>
                    <div style={{ fontSize: '0.75rem', color: '#64748b' }}>{cl.customerName || '—'}</div>
                  </td>
                  <td style={{ padding: '0.75rem 1rem', color: '#dc2626', fontWeight: 600 }}>
                    {cl.reason || 'Cancelación de pedido'}
                  </td>
                  <td style={{ padding: '0.75rem 1rem' }}>
                    <span style={{ background: '#fee2e2', color: '#991b1b', border: '1px solid #fca5a5', padding: '0.2rem 0.6rem', borderRadius: '12px', fontWeight: 800, fontSize: '0.72rem' }}>
                      CANCELADA
                    </span>
                  </td>
                  <td style={{ padding: '0.75rem 1rem', textAlign: 'center' }}>
                    <a
                      href={`/pedidos/print-labels/${cl.id}?cancelled=true`}
                      target="_blank"
                      rel="noopener noreferrer"
                      style={{
                        display: 'inline-flex',
                        alignItems: 'center',
                        gap: '0.35rem',
                        padding: '0.35rem 0.85rem',
                        background: '#fff',
                        color: '#dc2626',
                        border: '1.5px solid #dc2626',
                        borderRadius: '6px',
                        fontWeight: 700,
                        fontSize: '0.78rem',
                        textDecoration: 'none'
                      }}
                    >
                      🖨️ Ver Etiqueta
                    </a>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )}

  {/* Photo preview modal */}
  {previewPhoto && (
    <div
      onClick={() => setPreviewPhoto(null)}
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1200, padding: '1rem', cursor: 'pointer' }}
    >
      <div style={{ background: '#fff', padding: '0.5rem', borderRadius: '8px', maxWidth: '90vw', maxHeight: '90vh' }}>
        <img src={previewPhoto} alt="Evidencia QC" style={{ maxWidth: '100%', maxHeight: '85vh', borderRadius: '4px', display: 'block' }} />
      </div>
    </div>
  )}

      {/* ── MODAL: REJECT QC (Image 4) ────────────────────────────────────── */}
      {rejectModalOpen && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1100, padding: '1rem' }}>
          <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '560px', maxWidth: '95vw', maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 25px 50px rgba(0,0,0,0.3)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1.25rem', borderBottom: '2px solid #fee2e2', paddingBottom: '0.75rem' }}>
              <div style={{ width: '40px', height: '40px', background: '#fee2e2', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.25rem' }}>
                🛡️
              </div>
              <div>
                <h2 style={{ margin: 0, fontSize: '1.3rem', color: '#991b1b', fontWeight: 900 }}>
                  REJECT QC (Control de Calidad)
                </h2>
                <div style={{ fontSize: '0.8rem', color: '#666' }}>
                  {selectedIds.size} caja(s) seleccionada(s) para rechazo
                </div>
              </div>
            </div>

            {/* Selected items summary */}
            <div style={{ background: '#f8fafc', padding: '0.75rem 1rem', borderRadius: '8px', marginBottom: '1.25rem', maxHeight: '140px', overflowY: 'auto', border: '1px solid #e2e8f0' }}>
              <div style={{ fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.35rem' }}>Cajas a rechazar:</div>
              {selectedItemsList.map(item => (
                <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.78rem', marginBottom: '0.2rem' }}>
                  <span><strong>BOX#{item.boxNumber}</strong> · {item.prodDesc} ({item.item})</span>
                  <span style={{ color: '#dc2626', fontWeight: 700 }}>${item.precioTotal.toFixed(2)}</span>
                </div>
              ))}
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem', marginBottom: '1.5rem' }}>
              <div>
                <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 700, color: '#334155', marginBottom: '0.3rem' }}>
                  Razón del Rechazo QC *
                </label>
                <select
                  value={rejectReason}
                  onChange={e => setRejectReason(e.target.value)}
                  style={{ width: '100%', padding: '0.6rem', border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.9rem', marginBottom: '0.5rem', fontWeight: 600 }}
                >
                  <option value="Flor marchita / Daño en frío">Flor marchita / Daño en frío</option>
                  <option value="Botrytis / Hongo en flor">Botrytis / Hongo en flor</option>
                  <option value="Tallos rotos o quebrados">Tallos rotos o quebrados</option>
                  <option value="Caja aplastada / Daño mecánico">Caja aplastada / Daño mecánico</option>
                  <option value="Puntos negros / Plaga">Puntos negros / Plaga</option>
                  <option value="Tamaño o longitud incorrecta">Tamaño o longitud incorrecta</option>
                  <option value="Color o variedad incorrecta">Color o variedad incorrecta</option>
                  <option value="Otro motivo">Otro motivo (especificar)</option>
                </select>
                {rejectReason === 'Otro motivo' && (
                  <input
                    placeholder="Escribe el motivo del rechazo..."
                    onChange={e => setRejectReason(e.target.value)}
                    style={{ width: '100%', padding: '0.55rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.85rem' }}
                  />
                )}
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 700, color: '#334155', marginBottom: '0.3rem' }}>
                  Comentario Adicional para la Finca / Recomendaciones
                </label>
                <textarea
                  rows={3}
                  placeholder="Describe las observaciones específicas o recomendaciones técnicas para la finca..."
                  value={rejectComment}
                  onChange={e => setRejectComment(e.target.value)}
                  style={{ width: '100%', padding: '0.6rem', border: '1px solid #cbd5e1', borderRadius: '8px', fontSize: '0.85rem', boxSizing: 'border-box' }}
                />
              </div>

              <div>
                <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 700, color: '#334155', marginBottom: '0.3rem' }}>
                  Foto / Evidencia del Daño (Opcional - URL o Archivo)
                </label>
                <input
                  type="file"
                  accept="image/*"
                  onChange={e => {
                    const file = e.target.files?.[0];
                    if (file) {
                      const reader = new FileReader();
                      reader.onload = () => setRejectPhotoUrl(reader.result as string);
                      reader.readAsDataURL(file);
                    }
                  }}
                  style={{ width: '100%', padding: '0.4rem', border: '1px solid #cbd5e1', borderRadius: '6px', fontSize: '0.85rem', marginBottom: '0.5rem' }}
                />
                {rejectPhotoUrl && (
                  <div style={{ textAlign: 'center', marginTop: '0.5rem' }}>
                    <img src={rejectPhotoUrl} alt="Evidencia QC" style={{ maxHeight: '120px', borderRadius: '6px', border: '1px solid #ddd' }} />
                  </div>
                )}
              </div>
            </div>

            <div style={{ background: '#fef3c7', padding: '0.75rem 1rem', borderRadius: '8px', fontSize: '0.8rem', color: '#92400e', marginBottom: '1.5rem', lineHeight: 1.4 }}>
              <strong>Efecto en el Sistema:</strong>
              <br />• Las órdenes volverán al status de <strong>NEW</strong> para poder ser recompradas.
              <br />• En el módulo de las fincas constará el registro de las cajas rechazadas.
              <br />• Se generará automáticamente la corrección / descuento en la factura de la finca.
            </div>

            <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
              <button
                type="button"
                onClick={() => setRejectModalOpen(false)}
                style={{ padding: '0.6rem 1.25rem', borderRadius: '8px', border: '1px solid #cbd5e1', background: '#fff', cursor: 'pointer' }}
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={handleRejectQc}
                disabled={rejecting}
                style={{ padding: '0.6rem 1.6rem', borderRadius: '8px', border: 'none', background: '#dc2626', color: '#fff', fontWeight: 800, cursor: 'pointer' }}
              >
                {rejecting ? 'Procesando...' : 'Confirmar Rechazo QC'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── MODAL: CHANGE AWB (Image 4) ──────────────────────────────────── */}
      {changeAwbModalOpen && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.65)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1100, padding: '1rem' }}>
          <div style={{ background: '#fff', borderRadius: '16px', padding: '2rem', width: '500px', maxWidth: '95vw', boxShadow: '0 25px 50px rgba(0,0,0,0.3)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', marginBottom: '1.25rem', borderBottom: '2px solid #fef08a', paddingBottom: '0.75rem' }}>
              <div style={{ width: '40px', height: '40px', background: '#fef9c3', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '1.25rem' }}>
                ✈️
              </div>
              <div>
                <h2 style={{ margin: 0, fontSize: '1.3rem', color: '#854d0e', fontWeight: 900 }}>
                  CHANGE AWB (Cambio de Guía Aérea)
                </h2>
                <div style={{ fontSize: '0.8rem', color: '#666' }}>
                  {selectedIds.size} caja(s) seleccionada(s) para reasignar AWB
                </div>
              </div>
            </div>

            <div style={{ marginBottom: '1.5rem' }}>
              <label style={{ display: 'block', fontSize: '0.82rem', fontWeight: 700, color: '#334155', marginBottom: '0.35rem' }}>
                Selecciona o ingresa la Nueva AWB *
              </label>
              <input
                list="guias-change-list"
                value={newAwbVal}
                onChange={e => setNewAwbVal(e.target.value)}
                placeholder="Ej. 729-45452032"
                style={{ width: '100%', padding: '0.6rem 0.8rem', border: '2px solid #cbd5e1', borderRadius: '8px', fontSize: '0.95rem', fontWeight: 700, fontFamily: 'monospace', boxSizing: 'border-box' }}
              />
              <datalist id="guias-change-list">
                {guias.map(g => (
                  <option key={g.id} value={g.awb}>{g.agency} · Deliver: {formatDateToYYYYMMDD(g.deliverDate)} (Master: {g.master})</option>
                ))}
              </datalist>
            </div>

            <div style={{ background: '#fefce8', border: '1px solid #fef08a', padding: '0.75rem 1rem', borderRadius: '8px', fontSize: '0.8rem', color: '#854d0e', marginBottom: '1.5rem', lineHeight: 1.4 }}>
              <strong>Comportamiento del Sistema:</strong>
              <br />• Se <strong>elimina el tracking actual</strong> asignado a estas cajas.
              <br />• Se <strong>mantiene la finca</strong> proveedora original.
              <br />• Se <strong>mantienen los códigos únicos (BOX#)</strong> de cada caja.
              <br />• La orden regresa a status <strong>FARM ASIGNED / CONFIRMED</strong>.
            </div>

            <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
              <button
                type="button"
                onClick={() => setChangeAwbModalOpen(false)}
                style={{ padding: '0.6rem 1.25rem', borderRadius: '8px', border: '1px solid #cbd5e1', background: '#fff', cursor: 'pointer' }}
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={handleChangeAwb}
                disabled={changingAwb || !newAwbVal.trim()}
                style={{ padding: '0.6rem 1.6rem', borderRadius: '8px', border: 'none', background: '#eab308', color: '#78350f', fontWeight: 900, cursor: 'pointer' }}
              >
                {changingAwb ? 'Guardando...' : 'Confirmar Cambio de AWB'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── MODAL: ESCÁNER DE CÁMARA PARA MÓVIL / TABLET ─────────────────── */}
      <CameraBarcodeScannerModal
        isOpen={cameraModalOpen}
        onClose={() => setCameraModalOpen(false)}
        onBoxReceived={res => {
          setScanMessage({ text: res.message, isError: res.isError });
          fetchItems();
        }}
      />

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