'use client';

import React, { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';

interface FarmUser {
  id: string;
  email: string;
  name: string;
  farmId: string;
  farmName: string;
}

interface VarietyPreview {
  variety: string;
  code: string;
  lengthCm: number;
  pack: number;
  stems: number;
  boxType: string;
  l: number;
  w: number;
  h: number;
  dimWeight: number;
  realWeight: number;
}

export default function FarmPortalPage() {
  const [currentUser, setCurrentUser] = useState<FarmUser | null>(null);
  const [farmsList, setFarmsList] = useState<any[]>([]);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loginError, setLoginError] = useState('');
  const [loggingIn, setLoggingIn] = useState(false);

  // Portal data
  const [activeTab, setActiveTab] = useState<'UPLOAD' | 'CATALOG' | 'ORDERS'>('UPLOAD');
  const [myBoxTypes, setMyBoxTypes] = useState<any[]>([]);
  const [myOrders, setMyOrders] = useState<any[]>([]);
  const [loadingData, setLoadingData] = useState(false);

  // Variety Upload State
  const [excelRows, setExcelRows] = useState<any[]>([]);
  const [previewList, setPreviewList] = useState<VarietyPreview[]>([]);
  const [uploading, setUploading] = useState(false);
  const [uploadSuccess, setUploadSuccess] = useState('');
  const [uploadError, setUploadError] = useState('');

  // Orders Tab Filters
  const [orderSearchItem, setOrderSearchItem] = useState('');
  const [orderSearchAwb, setOrderSearchAwb] = useState('');

  // Load farms on mount to support quick demo login or selection
  useEffect(() => {
    fetch('/api/farms')
      .then(r => r.json())
      .then(d => { if (Array.isArray(d)) setFarmsList(d); })
      .catch(() => {});

    // Check localStorage
    const saved = localStorage.getItem('usf_farm_user');
    if (saved) {
      try {
        const u = JSON.parse(saved);
        setCurrentUser(u);
      } catch {}
    }
  }, []);

  // Fetch portal data when user is active
  const loadPortalData = async (farmId: string) => {
    setLoadingData(true);
    try {
      const [boxesRes, ordersRes] = await Promise.all([
        fetch(`/api/parametros/boxtype?farmId=${farmId}`),
        fetch(`/api/orders?farmId=${farmId}`)
      ]);

      if (boxesRes.ok) {
        const boxesData = await boxesRes.json();
        if (Array.isArray(boxesData)) setMyBoxTypes(boxesData);
      }
      if (ordersRes.ok) {
        const allOrders = await ordersRes.json();
        if (Array.isArray(allOrders)) {
          // Filter lines assigned to this farm
          const myLines: any[] = [];
          allOrders.forEach((o: any) => {
            if (Array.isArray(o?.lines)) {
              o.lines.forEach((l: any) => {
                if (l.farmId === farmId || (l.farm?.name && currentUser?.farmName && l.farm.name.toLowerCase() === currentUser.farmName.toLowerCase())) {
                  myLines.push({ ...l, order: o });
                }
              });
            }
          });
          setMyOrders(myLines);
        }
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoadingData(false);
    }
  };

  useEffect(() => {
    if (currentUser?.farmId) {
      loadPortalData(currentUser.farmId);
    }
  }, [currentUser]);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoginError('');
    setLoggingIn(true);
    try {
      const res = await fetch('/api/farms/portal/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Credenciales incorrectas');

      const user: FarmUser = {
        id: data.user.id,
        email: data.user.email,
        name: data.user.name,
        farmId: data.user.farmId,
        farmName: data.user.farmName || 'Finca'
      };
      setCurrentUser(user);
      localStorage.setItem('usf_farm_user', JSON.stringify(user));
    } catch (err: any) {
      setLoginError(err.message);
    } finally {
      setLoggingIn(false);
    }
  };

  // Quick switch for admin testing
  const handleQuickFarmSelect = (f: any) => {
    const dummyUser: FarmUser = {
      id: `farm-${f.id}`,
      email: f.emailOrders || `contacto@${f.name.toLowerCase().replace(/\s+/g, '')}.com`,
      name: f.name,
      farmId: f.id,
      farmName: f.name
    };
    setCurrentUser(dummyUser);
    localStorage.setItem('usf_farm_user', JSON.stringify(dummyUser));
  };

  const handleLogout = () => {
    setCurrentUser(null);
    localStorage.removeItem('usf_farm_user');
  };

  // Calculate Rose bunch weight
  const getRoseBunchWeight = (lengthCm: number) => {
    if (lengthCm <= 40) return 1.6;
    if (lengthCm <= 50) return 1.8;
    if (lengthCm <= 60) return 2.0;
    return 2.5; // 70cm+
  };

  // Parse Excel file
  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadError('');
    setUploadSuccess('');
    const reader = new FileReader();

    reader.onload = (evt) => {
      try {
        const bstr = evt.target?.result;
        const wb = XLSX.read(bstr, { type: 'binary' });
        const ws = wb.Sheets[wb.SheetNames[0]];
        const rawGrid: any[][] = XLSX.utils.sheet_to_json(ws, { header: 1 });

        if (!rawGrid.length || rawGrid.length < 2) {
          setUploadError('El archivo Excel está vacío o no contiene filas de datos.');
          return;
        }

        const headerRow: any[] = rawGrid[0] || [];
        let colProduct = -1, colVariety = -1, colColor = -1;
        let colStemLength = -1, colBoxType = -1, colBoxL = -1, colBoxW = -1, colBoxH = -1;
        let colDim = -1, colPack = -1, colStems = -1, colTotal = -1, colRealWeight = -1;

        headerRow.forEach((h: any, idx: number) => {
          const str = String(h || '').trim().toLowerCase();
          if (/^prod/i.test(str)) colProduct = idx;
          else if (/^var/i.test(str)) colVariety = idx;
          else if (/^col/i.test(str)) colColor = idx;
          else if (/^box\s*type|tipo.*caja/i.test(str)) colBoxType = idx;
          else if (/^width|ancho/i.test(str)) colBoxW = idx;
          else if (/^height|alto/i.test(str)) colBoxH = idx;
          else if (/^dim/i.test(str)) colDim = idx;
          else if (/^pack|ramos/i.test(str)) colPack = idx;
          else if (/^stems|tallos/i.test(str)) colStems = idx;
          else if (/^total/i.test(str)) colTotal = idx;
          else if (/real.*weight|peso.*real/i.test(str)) colRealWeight = idx;
        });

        // Distinguir columnas duplicadas de Lenght / Longitud
        headerRow.forEach((h: any, idx: number) => {
          const str = String(h || '').trim().toLowerCase();
          if (/leng|long|tallo/i.test(str)) {
            if (colBoxType !== -1 && idx < colBoxType) {
              colStemLength = idx;
            } else {
              colBoxL = idx;
            }
          }
        });

        if (colProduct === -1) colProduct = 0;
        if (colVariety === -1) colVariety = 1;
        if (colColor === -1) colColor = 2;
        if (colStemLength === -1) colStemLength = 3;
        if (colBoxType === -1) colBoxType = 4;
        if (colBoxL === -1) colBoxL = 5;
        if (colBoxW === -1) colBoxW = 6;
        if (colBoxH === -1) colBoxH = 7;
        if (colDim === -1) colDim = 8;
        if (colPack === -1) colPack = 9;
        if (colStems === -1) colStems = 10;
        if (colTotal === -1) colTotal = 11;
        if (colRealWeight === -1) colRealWeight = 12;

        const preparedRows: any[] = [];
        const previews: VarietyPreview[] = [];

        for (let i = 1; i < rawGrid.length; i++) {
          const row = rawGrid[i];
          if (!row || row.length === 0) continue;

          const product = String(row[colProduct] || 'Rose').trim();
          const variety = String(row[colVariety] || row[colProduct] || `VARIEDAD-${i}`).trim();
          if (!variety) continue;

          const color = String(row[colColor] || '').trim();

          const rawStem = String(row[colStemLength] || '');
          const lengthCm = parseFloat(rawStem.replace(/[^\d.]/g, '')) || 50;

          const rawBox = String(row[colBoxType] || 'EB').trim().toUpperCase();
          const boxType = rawBox || 'EB';

          const l = parseFloat(row[colBoxL]) || 104;
          const w = parseFloat(row[colBoxW]) || 18;
          const h = parseFloat(row[colBoxH]) || 14;

          const pack = parseInt(row[colPack], 10) || 0;
          // Regla: si el pack dice 0, no se debe subir esa línea
          if (!pack || pack <= 0) continue;

          const stems = parseInt(row[colStems], 10) || 25;
          const total = parseInt(row[colTotal], 10) || (pack * stems);

          const dimWeight = Math.round(((l * w * h) / 6000) * 100) / 100;

          let realWeight = parseFloat(row[colRealWeight]) || 0;
          if (!realWeight || realWeight <= 0) {
            if (/ros[ea]/i.test(product) || !product) {
              const bunchWeight = getRoseBunchWeight(lengthCm);
              realWeight = Math.round((pack * bunchWeight) * 100) / 100;
            }
          }

          preparedRows.push({
            product,
            variety,
            color,
            lengthCm,
            boxType,
            l,
            w,
            h,
            pack,
            stems,
            total,
            dimWeight,
            realWeight
          });

          previews.push({
            variety,
            code: variety.slice(0, 10).toUpperCase(),
            lengthCm,
            pack,
            stems,
            boxType,
            l,
            w,
            h,
            dimWeight,
            realWeight
          });
        }

        setExcelRows(preparedRows);
        setPreviewList(previews);
      } catch (err: any) {
        setUploadError(`Error al leer archivo: ${err.message}`);
      }
    };

    reader.readAsBinaryString(file);
  };

  const handleSaveVarieties = async () => {
    if (!currentUser?.farmId || !excelRows.length) return;
    setUploading(true);
    setUploadError('');
    setUploadSuccess('');
    try {
      const res = await fetch('/api/farms/varieties/upload', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          farmId: currentUser.farmId,
          farmName: currentUser.farmName,
          rows: excelRows
        })
      });

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

      setUploadSuccess(`¡Excelente! ${data.message}`);
      setExcelRows([]);
      setPreviewList([]);
      loadPortalData(currentUser.farmId);
    } catch (err: any) {
      setUploadError(err.message);
    } finally {
      setUploading(false);
    }
  };

  const downloadSampleExcel = () => {
    const sample = [
      {
        'VARIETY': 'EXPLORER',
        'CODE': 'RO-EXP-50',
        'LENGTH': 50,
        'PACK': 8,
        'STEMS': 25,
        'BOX TYPE': 'EB',
        'L': 104,
        'W': 18,
        'H': 14,
        'REAL WEIGHT': '',
        'DIM WEIGHT': ''
      },
      {
        'VARIETY': 'MONDIAL',
        'CODE': 'RO-MON-60',
        'LENGTH': 60,
        'PACK': 8,
        'STEMS': 25,
        'BOX TYPE': 'EB',
        'L': 104,
        'W': 18,
        'H': 14,
        'REAL WEIGHT': '',
        'DIM WEIGHT': ''
      },
      {
        'VARIETY': 'FREEDOM',
        'CODE': 'RO-FRD-40',
        'LENGTH': 40,
        'PACK': 10,
        'STEMS': 25,
        'BOX TYPE': 'EB',
        'L': 104,
        'W': 15,
        'H': 15,
        'REAL WEIGHT': '',
        'DIM WEIGHT': ''
      },
      {
        'VARIETY': 'PLAYA BLANCA',
        'CODE': 'RO-PBL-70',
        'LENGTH': 70,
        'PACK': 6,
        'STEMS': 25,
        'BOX TYPE': 'EB',
        'L': 104,
        'W': 18,
        'H': 14,
        'REAL WEIGHT': '',
        'DIM WEIGHT': ''
      }
    ];

    const ws = XLSX.utils.json_to_sheet(sample);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Variedades y Cajas');
    XLSX.writeFile(wb, `Plantilla_Variedades_Cajas_${currentUser?.farmName || 'Finca'}.xlsx`);
  };

  // If not logged in, render clean modern Login Screen
  if (!currentUser) {
    return (
      <div style={{
        minHeight: '100vh',
        background: 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '1.5rem',
        fontFamily: 'Inter, system-ui, sans-serif'
      }}>
        <div style={{
          background: '#fff',
          borderRadius: '24px',
          padding: '2.5rem',
          maxWidth: '440px',
          width: '100%',
          boxShadow: '0 25px 50px -12px rgba(0,0,0,0.5)',
          border: '1px solid #e2e8f0'
        }}>
          <div style={{ textAlign: 'center', marginBottom: '2rem' }}>
            <div style={{
              width: '80px',
              height: '80px',
              margin: '0 auto 1rem',
              borderRadius: '50%',
              background: '#f8fafc',
              border: '2px solid #e2e8f0',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              overflow: 'hidden'
            }}>
              <img
                src="/logo_usflorals_circle.png"
                alt="US Florals"
                style={{ width: '70px', height: '70px', objectFit: 'contain' }}
              />
            </div>
            <h1 style={{ fontSize: '1.5rem', fontWeight: 800, color: '#0f172a', margin: '0 0 0.25rem' }}>
              Portal de Fincas
            </h1>
            <p style={{ color: '#64748b', fontSize: '0.85rem', margin: 0 }}>
              US FLORALS &bull; Gestión de Variedades y Cajas
            </p>
          </div>

          {loginError && (
            <div style={{
              background: '#fef2f2',
              border: '1px solid #fecaca',
              color: '#b91c1c',
              padding: '0.75rem 1rem',
              borderRadius: '8px',
              fontSize: '0.85rem',
              marginBottom: '1.25rem',
              fontWeight: 600
            }}>
              ⚠️ {loginError}
            </div>
          )}

          <form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
            <div>
              <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, color: '#334155', marginBottom: '0.35rem' }}>
                Correo Electrónico o Usuario de Finca
              </label>
              <input
                type="text"
                required
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="ejemplo@finca.com o usuario"
                style={{
                  width: '100%',
                  padding: '0.75rem 1rem',
                  borderRadius: '10px',
                  border: '1.5px solid #cbd5e1',
                  fontSize: '0.9rem',
                  boxSizing: 'border-box'
                }}
              />
            </div>

            <div>
              <label style={{ display: 'block', fontSize: '0.8rem', fontWeight: 700, color: '#334155', marginBottom: '0.35rem' }}>
                Contraseña
              </label>
              <input
                type="password"
                required
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="••••••••"
                style={{
                  width: '100%',
                  padding: '0.75rem 1rem',
                  borderRadius: '10px',
                  border: '1.5px solid #cbd5e1',
                  fontSize: '0.9rem',
                  boxSizing: 'border-box'
                }}
              />
            </div>

            <button
              type="submit"
              disabled={loggingIn}
              style={{
                width: '100%',
                padding: '0.85rem',
                borderRadius: '12px',
                border: 'none',
                background: 'linear-gradient(135deg, #1c5236, #059669)',
                color: '#fff',
                fontSize: '0.95rem',
                fontWeight: 700,
                cursor: 'pointer',
                marginTop: '0.5rem',
                boxShadow: '0 4px 12px rgba(5, 150, 105, 0.3)'
              }}
            >
              {loggingIn ? 'Ingresando...' : 'Iniciar Sesión'}
            </button>
          </form>

          {/* Quick Access Helper for registered farms */}
          {farmsList.length > 0 && (
            <div style={{ marginTop: '2rem', paddingTop: '1.25rem', borderTop: '1px solid #e2e8f0' }}>
              <p style={{ fontSize: '0.75rem', fontWeight: 700, color: '#64748b', marginBottom: '0.5rem', textAlign: 'center' }}>
                Acceso Rápido por Finca (Modo Asistido):
              </p>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.4rem', justifyContent: 'center' }}>
                {farmsList.slice(0, 6).map(f => (
                  <button
                    key={f.id}
                    onClick={() => handleQuickFarmSelect(f)}
                    style={{
                      background: '#f8fafc',
                      border: '1px solid #cbd5e1',
                      borderRadius: '16px',
                      padding: '0.3rem 0.65rem',
                      fontSize: '0.75rem',
                      color: '#1e293b',
                      cursor: 'pointer',
                      fontWeight: 600
                    }}
                  >
                    🌻 {f.name}
                  </button>
                ))}
              </div>
            </div>
          )}

          <div style={{ textAlign: 'center', marginTop: '1.5rem' }}>
            <a href="/pedidos" style={{ color: '#059669', fontSize: '0.8rem', textDecoration: 'none', fontWeight: 600 }}>
              &larr; Volver al Sistema Principal
            </a>
          </div>
        </div>
      </div>
    );
  }

  // Logged-in Portal UI
  return (
    <div style={{ minHeight: '100vh', background: '#f8fafc', fontFamily: 'Inter, system-ui, sans-serif' }}>
      {/* Top Navbar */}
      <header style={{
        background: '#fff',
        borderBottom: '1px solid #e2e8f0',
        padding: '0.75rem 2rem',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        flexWrap: 'wrap',
        gap: '1rem'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
          <img src="/logo_usflorals_circle.png" alt="US Florals" style={{ width: '42px', height: '42px', objectFit: 'contain' }} />
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
              <h1 style={{ margin: 0, fontSize: '1.15rem', fontWeight: 800, color: '#0f172a' }}>
                {currentUser.farmName}
              </h1>
              <span style={{ fontSize: '0.7rem', fontWeight: 700, background: '#dcfce7', color: '#166534', padding: '0.15rem 0.5rem', borderRadius: '12px' }}>
                Finca Proveedora
              </span>
            </div>
            <p style={{ margin: 0, fontSize: '0.75rem', color: '#64748b' }}>
              Portal de Carga de Variedades, Cajas y Despachos
            </p>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
          <a
            href="/farms"
            style={{
              padding: '0.45rem 0.9rem',
              borderRadius: '8px',
              border: '1px solid #cbd5e1',
              background: '#fff',
              color: '#334155',
              fontSize: '0.8rem',
              fontWeight: 600,
              textDecoration: 'none'
            }}
          >
            Módulo Fincas (Admin)
          </a>
          <button
            onClick={handleLogout}
            style={{
              padding: '0.45rem 0.9rem',
              borderRadius: '8px',
              border: '1px solid #fecaca',
              background: '#fef2f2',
              color: '#b91c1c',
              fontSize: '0.8rem',
              fontWeight: 700,
              cursor: 'pointer'
            }}
          >
            Cerrar Sesión
          </button>
        </div>
      </header>

      {/* Main Container */}
      <main style={{ maxWidth: '1200px', margin: '1.5rem auto', padding: '0 1rem' }}>
        {/* Navigation Tabs */}
        <div style={{ display: 'flex', gap: '0.5rem', borderBottom: '2px solid #e2e8f0', marginBottom: '1.5rem' }}>
          <button
            onClick={() => setActiveTab('UPLOAD')}
            style={{
              padding: '0.65rem 1.25rem',
              border: 'none',
              background: 'transparent',
              borderBottom: activeTab === 'UPLOAD' ? '3px solid #059669' : '3px solid transparent',
              color: activeTab === 'UPLOAD' ? '#059669' : '#64748b',
              fontWeight: 700,
              fontSize: '0.9rem',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '0.4rem'
            }}
          >
            <span>📥 Subir Excel de Variedades</span>
          </button>

          <button
            onClick={() => setActiveTab('CATALOG')}
            style={{
              padding: '0.65rem 1.25rem',
              border: 'none',
              background: 'transparent',
              borderBottom: activeTab === 'CATALOG' ? '3px solid #059669' : '3px solid transparent',
              color: activeTab === 'CATALOG' ? '#059669' : '#64748b',
              fontWeight: 700,
              fontSize: '0.9rem',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '0.4rem'
            }}
          >
            <span>📦 Mis Cajas y Variedades ({myBoxTypes.length})</span>
          </button>

          <button
            onClick={() => setActiveTab('ORDERS')}
            style={{
              padding: '0.65rem 1.25rem',
              border: 'none',
              background: 'transparent',
              borderBottom: activeTab === 'ORDERS' ? '3px solid #059669' : '3px solid transparent',
              color: activeTab === 'ORDERS' ? '#059669' : '#64748b',
              fontWeight: 700,
              fontSize: '0.9rem',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '0.4rem'
            }}
          >
            <span>📋 Pedidos Asignados ({myOrders.length})</span>
          </button>
        </div>

        {/* TAB 1: UPLOAD */}
        {activeTab === 'UPLOAD' && (
          <div>
            <div style={{
              background: '#fff',
              borderRadius: '16px',
              padding: '2rem',
              boxShadow: '0 2px 12px rgba(0,0,0,0.05)',
              marginBottom: '1.5rem',
              border: '1px solid #e2e8f0'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: '1rem', marginBottom: '1.5rem' }}>
                <div>
                  <h2 style={{ fontSize: '1.3rem', fontWeight: 800, color: '#0f172a', margin: '0 0 0.25rem' }}>
                    Carga de Catálogo de Variedades y Dimensiones de Caja
                  </h2>
                  <p style={{ color: '#64748b', fontSize: '0.85rem', margin: 0, lineHeight: 1.5 }}>
                    Sube tu archivo Excel con las variedades que produce tu finca, longitud de tallos, ramos por caja y dimensiones.
                    El sistema calculará automáticamente el <strong>Peso Real</strong> (según tallo) y el <strong>Peso Dimensional</strong>.
                  </p>
                </div>
                <button
                  onClick={downloadSampleExcel}
                  style={{
                    padding: '0.6rem 1.1rem',
                    borderRadius: '10px',
                    border: '1px solid #059669',
                    background: '#ecfdf5',
                    color: '#059669',
                    fontWeight: 700,
                    fontSize: '0.85rem',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.4rem'
                  }}
                >
                  <span>📥 Descargar Plantilla Excel</span>
                </button>
              </div>

              {/* Regla de Peso Real de Rosas */}
              <div style={{
                background: '#f8fafc',
                border: '1px solid #cbd5e1',
                borderRadius: '12px',
                padding: '1rem 1.25rem',
                marginBottom: '1.5rem',
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
                gap: '1rem'
              }}>
                <div>
                  <span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#64748b', display: 'block' }}>FÓRMULA ROSAS (POR RAMO):</span>
                  <div style={{ fontSize: '0.85rem', color: '#1e293b', fontWeight: 600, marginTop: '0.2rem' }}>
                    40cm: 1.6 kg &bull; 50cm: 1.8 kg<br />
                    60cm: 2.0 kg &bull; 70cm+: 2.5 kg
                  </div>
                </div>
                <div>
                  <span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#64748b', display: 'block' }}>PESO REAL CAJA:</span>
                  <div style={{ fontSize: '0.85rem', color: '#1e293b', fontWeight: 600, marginTop: '0.2rem' }}>
                    Pack (Ramos) &times; Peso por ramo
                  </div>
                </div>
                <div>
                  <span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#64748b', display: 'block' }}>PESO DIMENSIONAL (DIM):</span>
                  <div style={{ fontSize: '0.85rem', color: '#1e293b', fontWeight: 600, marginTop: '0.2rem' }}>
                    (Largo &times; Ancho &times; Alto) / 6000
                  </div>
                </div>
              </div>

              {/* Upload Zone */}
              <div style={{
                border: '2px dashed #94a3b8',
                borderRadius: '16px',
                padding: '2.5rem 1.5rem',
                textAlign: 'center',
                background: '#f8fafc',
                cursor: 'pointer'
              }}>
                <div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📊</div>
                <h3 style={{ fontSize: '1rem', fontWeight: 700, color: '#1e293b', margin: '0 0 0.25rem' }}>
                  Selecciona o arrastra el archivo Excel (.xlsx / .xls)
                </h3>
                <p style={{ fontSize: '0.8rem', color: '#64748b', margin: '0 0 1rem' }}>
                  Asegúrate de que contenga las columnas: VARIETY, LENGTH, PACK, STEMS, BOX TYPE, L, W, H.
                </p>
                <input
                  type="file"
                  accept=".xlsx, .xls"
                  onChange={handleFileUpload}
                  style={{ display: 'none' }}
                  id="excel-file-input"
                />
                <label
                  htmlFor="excel-file-input"
                  style={{
                    display: 'inline-block',
                    padding: '0.65rem 1.5rem',
                    borderRadius: '10px',
                    background: '#059669',
                    color: '#fff',
                    fontWeight: 700,
                    fontSize: '0.85rem',
                    cursor: 'pointer'
                  }}
                >
                  Examinar Archivo
                </label>
              </div>

              {uploadError && (
                <div style={{ marginTop: '1rem', padding: '0.75rem 1rem', background: '#fef2f2', border: '1px solid #fecaca', color: '#b91c1c', borderRadius: '8px', fontSize: '0.85rem', fontWeight: 600 }}>
                  ⚠️ {uploadError}
                </div>
              )}

              {uploadSuccess && (
                <div style={{ marginTop: '1rem', padding: '0.75rem 1rem', background: '#ecfdf5', border: '1px solid #a7f3d0', color: '#065f46', borderRadius: '8px', fontSize: '0.85rem', fontWeight: 600 }}>
                  ✅ {uploadSuccess}
                </div>
              )}
            </div>

            {/* Live Preview Table */}
            {previewList.length > 0 && (
              <div style={{
                background: '#fff',
                borderRadius: '16px',
                padding: '1.5rem',
                boxShadow: '0 2px 12px rgba(0,0,0,0.05)',
                border: '1px solid #e2e8f0'
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
                  <h3 style={{ margin: 0, fontSize: '1.1rem', fontWeight: 800, color: '#0f172a' }}>
                    Vista Previa y Cálculos ({previewList.length} variedades detectadas)
                  </h3>
                  <button
                    onClick={handleSaveVarieties}
                    disabled={uploading}
                    style={{
                      padding: '0.65rem 1.5rem',
                      borderRadius: '10px',
                      background: 'linear-gradient(135deg, #1c5236, #059669)',
                      color: '#fff',
                      fontWeight: 800,
                      fontSize: '0.9rem',
                      border: 'none',
                      cursor: 'pointer'
                    }}
                  >
                    {uploading ? 'Guardando...' : `Confirmar y Cargar ${previewList.length} Variedades`}
                  </button>
                </div>

                <div style={{ overflowX: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.85rem' }}>
                    <thead>
                      <tr style={{ background: '#f1f5f9', color: '#334155' }}>
                        <th style={{ padding: '0.6rem', textAlign: 'left' }}>Variedad</th>
                        <th style={{ padding: '0.6rem', textAlign: 'center' }}>Tallo (cm)</th>
                        <th style={{ padding: '0.6rem', textAlign: 'center' }}>Pack (Ramos)</th>
                        <th style={{ padding: '0.6rem', textAlign: 'center' }}>Tallos/Ramo</th>
                        <th style={{ padding: '0.6rem', textAlign: 'center' }}>Caja</th>
                        <th style={{ padding: '0.6rem', textAlign: 'center' }}>Dimensiones (LxWxH)</th>
                        <th style={{ padding: '0.6rem', textAlign: 'center', background: '#ecfdf5', color: '#065f46' }}>Peso Real Calc (kg)</th>
                        <th style={{ padding: '0.6rem', textAlign: 'center', background: '#eff6ff', color: '#1e40af' }}>Peso DIM Calc (kg)</th>
                      </tr>
                    </thead>
                    <tbody>
                      {previewList.map((p, idx) => (
                        <tr key={idx} style={{ borderBottom: '1px solid #e2e8f0', background: idx % 2 === 0 ? '#fff' : '#f8fafc' }}>
                          <td style={{ padding: '0.6rem', fontWeight: 700, color: '#0f172a' }}>{p.variety}</td>
                          <td style={{ padding: '0.6rem', textAlign: 'center' }}>{p.lengthCm} cm</td>
                          <td style={{ padding: '0.6rem', textAlign: 'center', fontWeight: 600 }}>{p.pack}</td>
                          <td style={{ padding: '0.6rem', textAlign: 'center' }}>{p.stems}</td>
                          <td style={{ padding: '0.6rem', textAlign: 'center', fontWeight: 700, color: '#059669' }}>{p.boxType}</td>
                          <td style={{ padding: '0.6rem', textAlign: 'center', fontFamily: 'monospace' }}>{p.l} &times; {p.w} &times; {p.h} cm</td>
                          <td style={{ padding: '0.6rem', textAlign: 'center', fontWeight: 800, color: '#059669', background: '#f0fdf4' }}>{p.realWeight} kg</td>
                          <td style={{ padding: '0.6rem', textAlign: 'center', fontWeight: 800, color: '#2563eb', background: '#f8fafc' }}>{p.dimWeight} kg</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
          </div>
        )}

        {/* TAB 2: CATALOG */}
        {activeTab === 'CATALOG' && (
          <div style={{
            background: '#fff',
            borderRadius: '16px',
            padding: '2rem',
            boxShadow: '0 2px 12px rgba(0,0,0,0.05)',
            border: '1px solid #e2e8f0'
          }}>
            <h2 style={{ fontSize: '1.25rem', fontWeight: 800, color: '#0f172a', marginBottom: '1rem' }}>
              Tipos de Caja y Variedades de {currentUser.farmName}
            </h2>
            {myBoxTypes.length === 0 ? (
              <p style={{ color: '#64748b', fontSize: '0.9rem' }}>
                Aún no tienes cajas ni variedades registradas. Ve a la pestaña &quot;Subir Excel de Variedades&quot; para cargar tu catálogo.
              </p>
            ) : (
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.85rem' }}>
                  <thead>
                    <tr style={{ background: '#f1f5f9', color: '#334155' }}>
                      <th style={{ padding: '0.65rem 1rem', textAlign: 'left' }}>Código BoxType</th>
                      <th style={{ padding: '0.65rem 1rem', textAlign: 'left' }}>Nombre Descriptivo</th>
                      <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Largo (cm)</th>
                      <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Ancho (cm)</th>
                      <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Alto (cm)</th>
                      <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Peso Real (kg)</th>
                      <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Peso Dim (kg)</th>
                    </tr>
                  </thead>
                  <tbody>
                    {myBoxTypes.map((b, idx) => (
                      <tr key={b.id || idx} style={{ borderBottom: '1px solid #e2e8f0', background: idx % 2 === 0 ? '#fff' : '#f8fafc' }}>
                        <td style={{ padding: '0.65rem 1rem', fontWeight: 700, color: '#059669', fontFamily: 'monospace' }}>{b.code}</td>
                        <td style={{ padding: '0.65rem 1rem', fontWeight: 600 }}>{b.name}</td>
                        <td style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>{b.length ?? '—'}</td>
                        <td style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>{b.width ?? '—'}</td>
                        <td style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>{b.height ?? '—'}</td>
                        <td style={{ padding: '0.65rem 1rem', textAlign: 'center', fontWeight: 700, color: '#059669' }}>{b.realWeight ?? '—'}</td>
                        <td style={{ padding: '0.65rem 1rem', textAlign: 'center', fontWeight: 700, color: '#2563eb' }}>{b.dimWeight ?? '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}

        {/* TAB 3: ORDERS */}
        {activeTab === 'ORDERS' && (() => {
          const filteredOrders = myOrders.filter(l => {
            if (orderSearchItem) {
              const query = orderSearchItem.toLowerCase();
              const itemCode = (l.product?.code || '').toLowerCase();
              const itemName = (l.product?.name || '').toLowerCase();
              const po = (l.order?.po || '').toLowerCase();
              if (!itemCode.includes(query) && !itemName.includes(query) && !po.includes(query)) return false;
            }
            if (orderSearchAwb) {
              const awb = (l.order?.awb || l.airwayBill || '').toLowerCase();
              if (!awb.includes(orderSearchAwb.toLowerCase())) return false;
            }
            return true;
          });

          const isLineReceived = (st?: string) => {
            const s = (st || '').toUpperCase();
            return s === 'RECEIVED' || s === 'RECIBIDO' || s === 'SHIPPED';
          };

          const pendingPrintableIds = filteredOrders
            .filter(l => !isLineReceived(l.status))
            .map(l => l.id);

          return (
            <div style={{
              background: '#fff',
              borderRadius: '16px',
              padding: '2rem',
              boxShadow: '0 2px 12px rgba(0,0,0,0.05)',
              border: '1px solid #e2e8f0'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem', flexWrap: 'wrap', gap: '1rem' }}>
                <div>
                  <h2 style={{ fontSize: '1.25rem', fontWeight: 800, color: '#0f172a', margin: '0 0 0.25rem' }}>
                    Cajas y Pedidos Asignados a {currentUser.farmName}
                  </h2>
                  <p style={{ color: '#64748b', fontSize: '0.85rem', margin: 0 }}>
                    Consulta las órdenes asignadas a tu finca, descarga etiquetas Zebra y verifica estados de entrega.
                  </p>
                </div>
                {pendingPrintableIds.length > 0 && (
                  <button
                    type="button"
                    onClick={() => window.open(`/pedidos/print-labels/batch?ids=${pendingPrintableIds.join(',')}`, '_blank')}
                    style={{
                      padding: '0.55rem 1.1rem',
                      borderRadius: '8px',
                      border: 'none',
                      background: '#16a34a',
                      color: '#fff',
                      fontSize: '0.85rem',
                      fontWeight: 800,
                      cursor: 'pointer',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '0.4rem',
                      boxShadow: '0 2px 6px rgba(22,163,74,0.3)'
                    }}
                  >
                    🏷️ Imprimir Todas las Etiquetas Pendientes ({pendingPrintableIds.length})
                  </button>
                )}
              </div>

              {/* Filtros de Búsqueda */}
              <div style={{ display: 'flex', gap: '0.75rem', marginBottom: '1.25rem', flexWrap: 'wrap', background: '#f8fafc', padding: '0.85rem 1rem', borderRadius: '10px', border: '1px solid #e2e8f0' }}>
                <div style={{ flex: 1, minWidth: '200px' }}>
                  <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.25rem' }}>
                    Buscar por Ítem, Producto o PO:
                  </label>
                  <input
                    type="text"
                    value={orderSearchItem}
                    onChange={e => setOrderSearchItem(e.target.value)}
                    placeholder="Ej. Freedom, 1002024, PO#..."
                    style={{ width: '100%', padding: '0.45rem 0.65rem', borderRadius: '6px', border: '1px solid #cbd5e1', fontSize: '0.82rem' }}
                  />
                </div>
                <div style={{ flex: 1, minWidth: '180px' }}>
                  <label style={{ display: 'block', fontSize: '0.75rem', fontWeight: 700, color: '#475569', marginBottom: '0.25rem' }}>
                    Buscar por Guía AWB:
                  </label>
                  <input
                    type="text"
                    value={orderSearchAwb}
                    onChange={e => setOrderSearchAwb(e.target.value)}
                    placeholder="Ej. 729-12345678"
                    style={{ width: '100%', padding: '0.45rem 0.65rem', borderRadius: '6px', border: '1px solid #cbd5e1', fontSize: '0.82rem', fontFamily: 'monospace' }}
                  />
                </div>
                {(orderSearchItem || orderSearchAwb) && (
                  <div style={{ display: 'flex', alignItems: 'flex-end' }}>
                    <button
                      type="button"
                      onClick={() => { setOrderSearchItem(''); setOrderSearchAwb(''); }}
                      style={{ padding: '0.45rem 0.85rem', borderRadius: '6px', border: '1px solid #cbd5e1', background: '#fff', fontSize: '0.8rem', cursor: 'pointer', fontWeight: 600, color: '#64748b' }}
                    >
                      Limpiar
                    </button>
                  </div>
                )}
              </div>

              {filteredOrders.length === 0 ? (
                <p style={{ color: '#64748b', fontSize: '0.9rem', textAlign: 'center', padding: '2rem' }}>
                  No se encontraron pedidos con los filtros aplicados.
                </p>
              ) : (
                <div style={{ overflowX: 'auto' }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.85rem' }}>
                    <thead>
                      <tr style={{ background: '#f1f5f9', color: '#334155' }}>
                        <th style={{ padding: '0.65rem 1rem', textAlign: 'left' }}>PO</th>
                        <th style={{ padding: '0.65rem 1rem', textAlign: 'left' }}>Order #</th>
                        <th style={{ padding: '0.65rem 1rem', textAlign: 'left' }}>Ítem / Producto</th>
                        <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Cantidad Cajas</th>
                        <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Entrega (Deliver)</th>
                        <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Salida Finca</th>
                        <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>AWB</th>
                        <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Estado</th>
                        <th style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>Etiqueta</th>
                      </tr>
                    </thead>
                    <tbody>
                      {filteredOrders.map((line, idx) => {
                        const received = isLineReceived(line.status);
                        return (
                          <tr key={line.id || idx} style={{ borderBottom: '1px solid #e2e8f0', background: idx % 2 === 0 ? '#fff' : '#f8fafc' }}>
                            <td style={{ padding: '0.65rem 1rem', fontWeight: 700, color: '#0f172a' }}>{line.order?.po}</td>
                            <td style={{ padding: '0.65rem 1rem', fontWeight: 600 }}>{line.order?.orderNumber}</td>
                            <td style={{ padding: '0.65rem 1rem' }}>
                              <span style={{ fontWeight: 700, color: '#059669' }}>{line.product?.code}</span> &bull; {line.product?.name}
                            </td>
                            <td style={{ padding: '0.65rem 1rem', textAlign: 'center', fontWeight: 800 }}>{line.quantity || 1}</td>
                            <td style={{ padding: '0.65rem 1rem', textAlign: 'center', fontWeight: 600, color: '#d97706' }}>
                              {line.order?.deliveryDate ? new Date(line.order.deliveryDate).toISOString().split('T')[0] : '—'}
                            </td>
                            <td style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>
                              {line.order?.shipdt || '—'}
                            </td>
                            <td style={{ padding: '0.65rem 1rem', textAlign: 'center', fontFamily: 'monospace', fontWeight: 700, color: '#2563eb' }}>
                              {line.order?.awb || '—'}
                            </td>
                            <td style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>
                              <span style={{
                                fontSize: '0.75rem',
                                fontWeight: 700,
                                background: received ? '#dcfce7' : '#e0f2fe',
                                color: received ? '#166534' : '#0369a1',
                                padding: '0.2rem 0.5rem',
                                borderRadius: '4px'
                              }}>
                                {line.status || 'PENDIENTE'}
                              </span>
                            </td>
                            <td style={{ padding: '0.65rem 1rem', textAlign: 'center' }}>
                              {received ? (
                                <span style={{ fontSize: '0.75rem', fontWeight: 700, color: '#94a3b8' }} title="Caja recibida en cuarto frío — Etiqueta inhabilitada">
                                  🔒 Recibido
                                </span>
                              ) : (
                                <button
                                  type="button"
                                  onClick={() => window.open(`/pedidos/print-labels/${line.id}`, '_blank')}
                                  style={{
                                    padding: '0.35rem 0.75rem',
                                    borderRadius: '6px',
                                    border: '1px solid #16a34a',
                                    background: '#ecfdf5',
                                    color: '#16a34a',
                                    fontSize: '0.75rem',
                                    fontWeight: 700,
                                    cursor: 'pointer'
                                  }}
                                  title="Imprimir etiqueta Zebra"
                                >
                                  🏷️ Imprimir
                                </button>
                              )}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          );
        })()}
      </main>
    </div>
  );
}
