'use client';

import MainLayout from '@/components/layout/MainLayout';
import { useState, useEffect, useRef } from 'react';
import * as XLSX from 'xlsx';

type HtsItem = {
  id: string;
  name: string;
  htsCode: string;
  nandina: string;
  dutyRateEC?: number | null;
  dutyRateCO?: number | null;
  dutyRateUS?: number | null;
  declaredValue?: number | null;
  description?: string | null;
};

const emptyForm = {
  name: '', htsCode: '', nandina: '', dutyRateEC: '', dutyRateCO: '', dutyRateUS: '', declaredValue: '', description: ''
};

// Datos pre-cargados del sistema anterior
const PRELOADED: Omit<HtsItem, 'id'>[] = [
  { name: 'ALSTROEMERIA',         htsCode: '0603.19.01.10', nandina: '0603190000', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.16, description: 'Fresh cut alstroemeria' },
  { name: 'ASIATIC LILIES',       htsCode: '0603.15.00.00', nandina: '0603150000', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.35, description: 'Fresh cut asiatic lilies' },
  { name: 'ASTER',                htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.10, description: 'Fresh cut aster' },
  { name: 'BELLS OF IRELAND',     htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.16, description: 'Fresh cut bells of ireland' },
  { name: 'CALLAS LEAVES',        htsCode: '0604.20.00.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.15, description: 'Fresh cut calla leaves' },
  { name: 'CARNATION',            htsCode: '0603.12.70.00', nandina: '0603129000', dutyRateEC: 6.4, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.12, description: 'Fresh cut carnations' },
  { name: 'MINI CARNATION',       htsCode: '0603.12.70.00', nandina: '0603129000', dutyRateEC: 6.4, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.10, description: 'Fresh cut mini carnations' },
  { name: 'CHRYSANTHEMUM',        htsCode: '0603.14.00.20', nandina: '0603149000', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.15, description: 'Fresh cut chrysanthemum' },
  { name: 'DELPHINIUM',           htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.20, description: 'Fresh cut delphinium' },
  { name: 'DIANTHUS',             htsCode: '0603.12.70.00', nandina: '0603129000', dutyRateEC: 6.4, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.18, description: 'Fresh cut dianthus' },
  { name: 'ROSES',                htsCode: '0603.11.00.10', nandina: '0603110010', dutyRateEC: 6.8, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.25, description: 'Fresh cut roses' },
  { name: 'SPRAY ROSES',          htsCode: '0603.11.00.10', nandina: '0603110010', dutyRateEC: 6.8, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.18, description: 'Fresh cut spray roses' },
  { name: 'GYPSOPHILA',           htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.12, description: 'Fresh cut gypsophila / baby breath' },
  { name: 'HYPERICUM',            htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.14, description: 'Fresh cut hypericum' },
  { name: 'HYDRANGEAS',           htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.45, description: 'Fresh cut hydrangeas' },
  { name: 'LISIANTHUS',           htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.20, description: 'Fresh cut lisianthus' },
  { name: 'LIMONIUM',             htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.10, description: 'Fresh cut limonium / statice' },
  { name: 'ORCHIDS',              htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.60, description: 'Fresh cut orchids' },
  { name: 'PEONIES',              htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.55, description: 'Fresh cut peonies' },
  { name: 'RANUNCULUS',           htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.22, description: 'Fresh cut ranunculus' },
  { name: 'SUNFLOWERS',           htsCode: '0603.19.01.60', nandina: '0603199090', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.18, description: 'Fresh cut sunflowers' },
  { name: 'TULIPS',               htsCode: '0603.13.00.00', nandina: '0603130000', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.25, description: 'Fresh cut tulips' },
  { name: 'GREENERY / FOLIAGE',   htsCode: '0604.90.60.00', nandina: '0604906000', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.08, description: 'Fresh cut greenery and foliage' },
  { name: 'SENECIO',              htsCode: '0604.90.60.00', nandina: '0604906000', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.08, description: 'Fresh cut senecio' },
  { name: 'RUSCUS',               htsCode: '0604.90.60.00', nandina: '0604906000', dutyRateEC: 4.0, dutyRateCO: 12.5, dutyRateUS: 0.0,  declaredValue: 0.10, description: 'Fresh cut ruscus' },
  { name: 'CERAMIC VASE',         htsCode: '6912.00.00.00', nandina: '69120000',   dutyRateEC: 0.0, dutyRateCO: 0.0, dutyRateUS: 0.0,   declaredValue: 0.50, description: 'Ceramic vase / accessories' },
];

export default function HtsPage() {
  const [items, setItems] = useState<HtsItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');
  const [seeding, setSeeding] = useState(false);

  // Excel Upload State
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [uploadData, setUploadData] = useState<any[]>([]);
  const [uploadFileName, setUploadFileName] = useState('');
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState('');
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const fetch_ = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/parametros/hts');
      if (res.ok) setItems(await res.json());
    } catch (e) { console.error(e); }
    setLoading(false);
  };

  useEffect(() => { fetch_(); }, []);

  const openNew = () => { setForm(emptyForm); setEditingId(null); setError(null); setShowModal(true); };

  const openEdit = (item: HtsItem) => {
    setForm({
      name: item.name,
      htsCode: item.htsCode,
      nandina: item.nandina,
      dutyRateEC: item.dutyRateEC?.toString() || '',
      dutyRateCO: item.dutyRateCO?.toString() || '',
      dutyRateUS: item.dutyRateUS?.toString() || '',
      declaredValue: item.declaredValue?.toString() || '',
      description: item.description || '',
    });
    setEditingId(item.id);
    setError(null);
    setShowModal(true);
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true); setError(null);
    try {
      const url = editingId ? `/api/parametros/hts/${editingId}` : '/api/parametros/hts';
      const method = editingId ? 'PUT' : 'POST';
      const res = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) });
      if (!res.ok) { const d = await res.json(); throw new Error(d.error || 'Error'); }
      setShowModal(false);
      fetch_();
    } catch (err: any) { setError(err.message); }
    setSaving(false);
  };

  const handleDelete = async (id: string) => {
    if (!window.confirm('¿Eliminar esta entrada del catálogo HTS?')) return;
    await fetch(`/api/parametros/hts/${id}`, { method: 'DELETE' });
    fetch_();
  };

  const handleSeedData = async () => {
    setSeeding(true);
    let created = 0;
    
    for (const item of PRELOADED) {
      try {
        const res = await fetch('/api/parametros/hts', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(item)
        });
        if (res.ok) created++;
      } catch {}
    }
    alert(`✅ Se cargaron ${created} entradas al catálogo HTS.`);
    fetch_();
    setSeeding(false);
  };

  // ── Excel Download Template ──────────────────────────────────────
  const handleDownloadTemplate = () => {
    window.open('/api/parametros/hts/template', '_blank');
  };

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

    setUploadFileName(file.name);
    setUploadError('');

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

        if (!data || data.length === 0) {
          setUploadError('El archivo seleccionado no contiene filas de datos.');
          setUploadData([]);
          return;
        }

        setUploadData(data);
      } catch (err: any) {
        setUploadError(`Error al leer el archivo Excel: ${err.message}`);
        setUploadData([]);
      }
    };
    reader.readAsBinaryString(file);
  };

  // ── Excel Upload & Save ──────────────────────────────────────────
  const handleUploadSubmit = async () => {
    if (uploadData.length === 0) {
      setUploadError('Por favor selecciona un archivo con datos válidos.');
      return;
    }

    setUploading(true);
    setUploadError('');

    try {
      const res = await fetch('/api/parametros/hts/upload', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ items: uploadData })
      });

      const result = await res.json();
      if (!res.ok) throw new Error(result.error || 'Error al importar datos');

      alert(`✅ Importación exitosa:\n• ${result.inserted} nuevos tipos de flor creados.\n• ${result.updated} tipos de flor actualizados.`);
      setShowUploadModal(false);
      setUploadData([]);
      setUploadFileName('');
      fetch_();
    } catch (err: any) {
      setUploadError(err.message);
    } finally {
      setUploading(false);
    }
  };

  const filtered = items.filter(i =>
    i.name.toLowerCase().includes(search.toLowerCase()) ||
    i.htsCode.toLowerCase().includes(search.toLowerCase()) ||
    i.nandina.toLowerCase().includes(search.toLowerCase())
  );

  const labelStyle: React.CSSProperties = { display: 'block', fontSize: '0.72rem', fontWeight: 700, marginBottom: '0.35rem', color: 'var(--primary-color)', textTransform: 'uppercase', letterSpacing: '0.05em' };

  const dutyBadge = (rate: number) => {
    const color = rate >= 6.8 ? '#dc2626' : rate >= 6.4 ? '#ea580c' : '#16a34a';
    return (
      <span style={{ background: color + '18', color, border: `1px solid ${color}44`, padding: '0.1rem 0.5rem', borderRadius: '12px', fontSize: '0.75rem', fontWeight: 700 }}>
        {rate}%
      </span>
    );
  };

  return (
    <MainLayout>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '2rem', flexWrap: 'wrap', gap: '1rem' }}>
        <div>
          <h1>Valor de Productos y HTS</h1>
          <p className="page-subtitle">Catálogo de tipos de flor con sus códigos arancelarios (HTS/Nandina) y tasas de arancel.</p>
        </div>
        <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
          <button
            className="btn-secondary"
            onClick={handleDownloadTemplate}
            title="Descargar plantilla Excel para llenar el catálogo HTS"
            style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', borderColor: '#0284c7', color: '#0284c7' }}
          >
            📥 Descargar Formato Excel
          </button>
          
          <button
            className="btn-secondary"
            onClick={() => {
              setUploadData([]);
              setUploadFileName('');
              setUploadError('');
              setShowUploadModal(true);
            }}
            title="Subir archivo Excel con lista de tipos de flor y códigos HTS"
            style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', borderColor: '#16a34a', color: '#16a34a' }}
          >
            📤 Subir Lista Excel (HTS)
          </button>

          {items.length === 0 && (
            <button className="btn-secondary" onClick={handleSeedData} disabled={seeding}
              style={{ borderColor: '#10b981', color: '#10b981' }}>
              {seeding ? 'Cargando...' : '⬇ Cargar Datos Predefinidos'}
            </button>
          )}

          <button className="btn-primary" onClick={openNew}>
            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" /></svg>
            Nuevo Tipo de Producto
          </button>
        </div>
      </div>

      <div style={{ marginBottom: '1.5rem' }}>
        <input placeholder="Buscar por nombre, HTS Code o Nandina..." value={search}
          onChange={e => setSearch(e.target.value)} style={{ maxWidth: '420px' }} />
      </div>

      <div className="table-container">
        <table>
          <thead>
            <tr>
              <th>Lista de Productos</th>
              <th>HTS Code (USA)</th>
              <th>Nandina (Ecuador)</th>
              <th>Duty EC</th>
              <th>Duty CO</th>
              <th>Duty US</th>
              <th>Costo Decl/Stem</th>
              <th>Descripción Aduana</th>
              <th>Acciones</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={9} style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-secondary)' }}>Cargando...</td></tr>
            ) : filtered.length === 0 ? (
              <tr><td colSpan={9} style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-secondary)' }}>
                {search ? 'Sin resultados.' : (
                  <div>
                    <p style={{ marginBottom: '1rem' }}>No hay tipos de producto en el catálogo.</p>
                    <button className="btn-primary" onClick={handleSeedData} disabled={seeding}>
                      {seeding ? 'Cargando...' : '⬇ Cargar Datos Predefinidos del Sistema Anterior'}
                    </button>
                  </div>
                )}
              </td></tr>
            ) : filtered.map(item => (
              <tr key={item.id}>
                <td style={{ fontWeight: 700, color: 'var(--primary-color)', fontSize: '0.85rem' }}>{item.name}</td>
                <td><code style={{ fontSize: '0.8rem', background: '#eff6ff', color: '#1d4ed8', padding: '0.15rem 0.5rem', borderRadius: '4px' }}>{item.htsCode}</code></td>
                <td><code style={{ fontSize: '0.8rem', background: '#f0fdf4', color: '#059669', padding: '0.15rem 0.5rem', borderRadius: '4px' }}>{item.nandina}</code></td>
                <td>{item.dutyRateEC != null ? dutyBadge(item.dutyRateEC) : '—'}</td>
                <td>{item.dutyRateCO != null ? dutyBadge(item.dutyRateCO) : '—'}</td>
                <td>{item.dutyRateUS != null ? dutyBadge(item.dutyRateUS) : '—'}</td>
                <td style={{ fontFamily: 'monospace', fontSize: '0.85rem' }}>{item.declaredValue != null ? `$${item.declaredValue.toFixed(2)}` : '—'}</td>
                <td style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.description || '—'}</td>
                <td>
                  <div style={{ display: 'flex', gap: '0.5rem' }}>
                    <button className="btn-secondary" style={{ padding: '0.25rem 0.75rem', fontSize: '0.75rem' }} onClick={() => openEdit(item)}>Editar</button>
                    <button className="btn-secondary" style={{ padding: '0.25rem 0.5rem', fontSize: '0.75rem', color: '#dc2626', borderColor: '#fca5a5' }} onClick={() => handleDelete(item.id)}>
                      <svg width="13" height="13" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* ── MODAL: SUBIR ARCHIVO EXCEL HTS ──────────────────────────────── */}
      {showUploadModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 60, background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
          <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '650px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)', animation: 'slideUp 0.3s ease' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem' }}>
              <h2 style={{ color: '#16a34a', fontSize: '1.3rem', fontWeight: 800, margin: 0, display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                📤 Cargar Lista HTS en Excel
              </h2>
              <button onClick={() => setShowUploadModal(false)} style={{ color: 'var(--text-secondary)', fontSize: '1.5rem', border: 'none', background: 'transparent', cursor: 'pointer' }}>×</button>
            </div>

            <p style={{ color: 'var(--text-secondary)', fontSize: '0.88rem', marginBottom: '1.25rem' }}>
              Sube un archivo Excel (.xlsx, .xls o .csv) con las columnas correspondientes al catálogo HTS y aranceles. Si un tipo de producto ya existe, sus códigos y aranceles se actualizarán automáticamente.
            </p>

            {/* Template download link inside modal */}
            <div style={{ background: '#eff6ff', border: '1px solid #bfdbfe', borderRadius: '8px', padding: '0.75rem 1rem', marginBottom: '1.25rem', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ fontSize: '0.82rem', color: '#1e40af' }}>
                ¿No tienes el formato? Descarga la plantilla oficial con ejemplos.
              </div>
              <button
                type="button"
                onClick={handleDownloadTemplate}
                style={{ padding: '0.35rem 0.8rem', borderRadius: '6px', border: 'none', background: '#2563eb', color: '#fff', fontSize: '0.8rem', fontWeight: 700, cursor: 'pointer' }}
              >
                Descargar Formato
              </button>
            </div>

            {/* File Dropzone / Selector */}
            <div
              onClick={() => fileInputRef.current?.click()}
              style={{
                border: '2px dashed #cbd5e1',
                borderRadius: '12px',
                padding: '2rem 1.5rem',
                textAlign: 'center',
                cursor: 'pointer',
                background: uploadFileName ? '#f0fdf4' : '#f8fafc',
                transition: 'all 0.2s ease',
                marginBottom: '1.25rem'
              }}
            >
              <input
                ref={fileInputRef}
                type="file"
                accept=".xlsx, .xls, .csv"
                onChange={handleFileChange}
                style={{ display: 'none' }}
              />
              <div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>
                {uploadFileName ? '📄' : '📁'}
              </div>
              <div style={{ fontWeight: 700, color: uploadFileName ? '#166534' : '#334155', fontSize: '0.95rem', marginBottom: '0.25rem' }}>
                {uploadFileName ? uploadFileName : 'Haz clic para seleccionar o arrastra tu archivo Excel'}
              </div>
              <div style={{ fontSize: '0.78rem', color: '#64748b' }}>
                Formatos compatibles: .xlsx, .xls, .csv
              </div>
            </div>

            {/* Preview of read rows */}
            {uploadData.length > 0 && (
              <div style={{ background: '#f8fafc', borderRadius: '8px', padding: '0.75rem 1rem', marginBottom: '1.25rem', border: '1px solid #e2e8f0' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5rem' }}>
                  <span style={{ fontWeight: 700, fontSize: '0.85rem', color: '#166534' }}>
                    ✓ {uploadData.length} fila(s) detectada(s) en el archivo
                  </span>
                  <span style={{ fontSize: '0.75rem', color: '#64748b' }}>Vista previa (primeras 3):</span>
                </div>
                <div style={{ maxHeight: '100px', overflowY: 'auto', fontSize: '0.78rem', fontFamily: 'monospace' }}>
                  {uploadData.slice(0, 3).map((r, i) => (
                    <div key={i} style={{ borderBottom: '1px solid #eee', padding: '0.2rem 0', color: '#334155' }}>
                      • {Object.values(r).slice(0, 4).join(' | ')}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {uploadError && (
              <div style={{ padding: '0.75rem', background: '#fef2f2', color: '#dc2626', borderRadius: '8px', fontSize: '0.85rem', marginBottom: '1.25rem' }}>
                {uploadError}
              </div>
            )}

            <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end' }}>
              <button
                type="button"
                className="btn-secondary"
                onClick={() => setShowUploadModal(false)}
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={handleUploadSubmit}
                disabled={uploading || uploadData.length === 0}
                style={{
                  padding: '0.6rem 1.6rem',
                  borderRadius: '8px',
                  border: 'none',
                  background: 'linear-gradient(135deg, #16a34a, #15803d)',
                  color: '#fff',
                  fontWeight: 700,
                  fontSize: '0.9rem',
                  cursor: uploading || uploadData.length === 0 ? 'not-allowed' : 'pointer'
                }}
              >
                {uploading ? 'Importando...' : `Importar ${uploadData.length > 0 ? uploadData.length + ' Productos' : 'Excel'}`}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── MODAL: MANUAL EDIT / CREATE HTS ─────────────────────────────── */}
      {showModal && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 50, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}>
          <div style={{ background: 'white', borderRadius: 'var(--radius-lg)', padding: '2rem', width: '100%', maxWidth: '600px', boxShadow: '0 25px 50px rgba(0,0,0,0.25)', animation: 'slideUp 0.3s ease' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
              <h2 style={{ color: 'var(--primary-color)', fontSize: '1.2rem', fontWeight: 700 }}>
                {editingId ? 'Editar Tipo de Producto HTS' : 'Nuevo Tipo de Producto HTS'}
              </h2>
              <button onClick={() => setShowModal(false)} style={{ color: 'var(--text-secondary)', fontSize: '1.5rem', border: 'none', background: 'transparent', cursor: 'pointer' }}>×</button>
            </div>

            <form onSubmit={handleSave} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '1rem' }}>
                <div>
                  <label style={labelStyle}>Nombre del Producto *</label>
                  <input required placeholder="Ej: ROSES, CARNATION, ALSTROEMERIA"
                    value={form.name} onChange={e => setForm({ ...form, name: e.target.value.toUpperCase() })} />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                <div>
                  <label style={labelStyle}>US HTS Code *</label>
                  <input required placeholder="Ej: 0603.11.00.10" value={form.htsCode}
                    onChange={e => setForm({ ...form, htsCode: e.target.value })}
                    style={{ fontFamily: 'monospace' }} />
                </div>
                <div>
                  <label style={labelStyle}>Nandina (Ecuador) *</label>
                  <input required placeholder="Ej: 0603110010" value={form.nandina}
                    onChange={e => setForm({ ...form, nandina: e.target.value })}
                    style={{ fontFamily: 'monospace' }} />
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '1rem' }}>
                <div>
                  <label style={labelStyle}>Duty EC (%)</label>
                  <input type="number" step="0.1" placeholder="Ej: 6.8"
                    value={form.dutyRateEC} onChange={e => setForm({ ...form, dutyRateEC: e.target.value })} />
                </div>
                <div>
                  <label style={labelStyle}>Duty CO (%)</label>
                  <input type="number" step="0.1" placeholder="Ej: 12.5"
                    value={form.dutyRateCO} onChange={e => setForm({ ...form, dutyRateCO: e.target.value })} />
                </div>
                <div>
                  <label style={labelStyle}>Duty USA (%)</label>
                  <input type="number" step="0.1" placeholder="Ej: 0"
                    value={form.dutyRateUS} onChange={e => setForm({ ...form, dutyRateUS: e.target.value })} />
                </div>
              </div>

              <div>
                <label style={labelStyle}>Costo Declarado por Stem ($)</label>
                <input type="number" step="0.01" placeholder="Ej: 0.25"
                  value={form.declaredValue} onChange={e => setForm({ ...form, declaredValue: e.target.value })} />
                <small style={{ color: 'var(--text-secondary)', fontSize: '0.7rem' }}>Valor declarado ante aduana por tallo</small>
              </div>

              <div>
                <label style={labelStyle}>Descripción para Aduana</label>
                <input placeholder="Ej: Fresh cut roses" value={form.description}
                  onChange={e => setForm({ ...form, description: e.target.value })} />
              </div>

              {/* Preview */}
              {form.htsCode && form.nandina && (
                <div style={{ background: 'linear-gradient(135deg, #eff6ff, #f0fdf4)', border: '1px solid #bfdbfe', borderRadius: '8px', padding: '0.75rem 1rem', display: 'flex', gap: '1.5rem', flexWrap: 'wrap' }}>
                  <span style={{ fontSize: '0.78rem' }}><strong>HTS:</strong> <code style={{ color: '#1d4ed8' }}>{form.htsCode}</code></span>
                  <span style={{ fontSize: '0.78rem' }}><strong>Nandina:</strong> <code style={{ color: '#059669' }}>{form.nandina}</code></span>
                </div>
              )}

              {error && <div style={{ padding: '0.75rem', background: '#fef2f2', color: '#dc2626', borderRadius: '8px', fontSize: '0.875rem' }}>{error}</div>}

              <div style={{ display: 'flex', gap: '1rem', justifyContent: 'flex-end' }}>
                <button type="button" className="btn-secondary" onClick={() => setShowModal(false)}>Cancelar</button>
                <button type="submit" className="btn-primary" disabled={saving}>
                  {saving ? 'Guardando...' : editingId ? 'Actualizar' : 'Guardar'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      <style>{`@keyframes slideUp { from { opacity:0; transform:translateY(20px);} to {opacity:1; transform:translateY(0);} }`}</style>
    </MainLayout>
  );
}
