'use client';

import { useState, useRef, useMemo } from 'react';
import * as XLSX from 'xlsx';
import ModalPortal from '@/components/common/ModalPortal';
import { addNotification } from '@/lib/notifications';

type FormatType = 'fedex' | 'ups' | 'unknown';

interface DuplicateRow {
  row: number;
  master: string;
  po: string;
  orderNumber: string;
  orderDate: string;
  deliveryDate: string;
  item: string;
  reason: string;
}

function detectFormat(headers: string[]): FormatType {
  const h = headers.map(x => x?.toString().toLowerCase());
  // UPS format has "tracking" and "custnbr" and "shipdt"
  if (h.includes('tracking') && h.includes('custnbr') && h.includes('shipdt')) return 'ups';
  // FedEx format has "tracking" and "custnbr" but not shipdt (or has different cols)
  if (h.includes('tracking') && h.includes('custnbr')) return 'fedex';
  return 'unknown';
}

export default function OrderUploadModal({ onClose, onUploadSuccess }: { onClose: () => void, onUploadSuccess: () => void }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [duplicateList, setDuplicateList] = useState<DuplicateRow[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [dragActive, setDragActive] = useState(false);
  const [detectedFormat, setDetectedFormat] = useState<FormatType | null>(null);
  const [forcedFormat, setForcedFormat] = useState<FormatType | 'auto'>('auto');
  const fileInputRef = useRef<HTMLInputElement>(null);

  const processFile = async (file: File) => {
    setLoading(true);
    setError(null);
    setDuplicateList([]);
    setSearchTerm('');
    setDetectedFormat(null);
    try {
      const data = await file.arrayBuffer();
      const workbook = XLSX.read(data);
      
      // For UPS files, try "Sheet1" first (has full data); fall back to first sheet
      let sheetName = workbook.SheetNames[0];
      let jsonData: any[] = [];
      let format: FormatType = 'unknown';

      // Try each sheet to find a format we recognize
      for (const sn of workbook.SheetNames) {
        const ws = workbook.Sheets[sn];
        const rows = XLSX.utils.sheet_to_json(ws, { defval: '' }) as any[];
        if (rows.length === 0) continue;

        const headers = Object.keys(rows[0]);
        const detected = detectFormat(headers);
        
        if (detected !== 'unknown') {
          format = detected;
          sheetName = sn;
          jsonData = rows;
          break;
        }
      }

      // If still unknown, just use first sheet
      if (format === 'unknown') {
        const ws = workbook.Sheets[workbook.SheetNames[0]];
        jsonData = XLSX.utils.sheet_to_json(ws, { defval: '' }) as any[];
        format = 'fedex'; // treat as fedex by default
      }

      // GET RAW DATA with A, B, C... keys
      const rawDataWithA = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { header: 'A', defval: '' }) as any[];

      const finalFormat = forcedFormat !== 'auto' ? forcedFormat : format;
      setDetectedFormat(finalFormat);

      const res = await fetch('/api/orders/import', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ data: jsonData, rawData: rawDataWithA, format: finalFormat }),
      });

      const responseData = await res.json();
      if (!res.ok) {
        if (Array.isArray(responseData.duplicateList) && responseData.duplicateList.length > 0) {
          setDuplicateList(responseData.duplicateList);
        }
        throw new Error(responseData.error || 'Error al procesar archivo');
      }

      if (responseData.duplicateCount > 0 && Array.isArray(responseData.duplicateList)) {
        setDuplicateList(responseData.duplicateList);
        addNotification({
          module: 'Órdenes',
          message: `⚠️ Se subieron ${responseData.createdOrders} órdenes. Se omitieron ${responseData.duplicateCount} líneas duplicadas del archivo.`,
          link: '/orders',
        });
        onUploadSuccess();
        // Mantener abierto para mostrar el resumen de qué líneas del archivo no se subieron
      } else {
        onUploadSuccess();
        onClose();
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      processFile(e.dataTransfer.files[0]);
    }
  };

  const formatLabel = (f: FormatType | null) => {
    if (f === 'ups') return '📦 Formato UPS detectado';
    if (f === 'fedex') return '✈️ Formato FedEx detectado';
    return null;
  };

  const exportDuplicatesCSV = () => {
    if (!duplicateList.length) return;
    const headers = ['Fila', 'PO', 'Order Number (CUSTnbr)', 'Cliente Master', 'Fecha Orden', 'Fecha Entrega', 'Item Number', 'Motivo'];
    const rows = duplicateList.map(d => [
      d.row,
      `"${(d.po || '').replace(/"/g, '""')}"`,
      `"${(d.orderNumber || '').replace(/"/g, '""')}"`,
      `"${(d.master || '').replace(/"/g, '""')}"`,
      `"${(d.orderDate || '').replace(/"/g, '""')}"`,
      `"${(d.deliveryDate || '').replace(/"/g, '""')}"`,
      `"${(d.item || '').replace(/"/g, '""')}"`,
      `"${(d.reason || '').replace(/"/g, '""')}"`,
    ]);
    const csvContent = '\uFEFF' + [headers.join(','), ...rows.map(r => r.join(','))].join('\r\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `ordenes_duplicadas_${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const filteredDuplicates = useMemo(() => {
    if (!searchTerm.trim()) return duplicateList;
    const term = searchTerm.toLowerCase().trim();
    return duplicateList.filter(d =>
      d.po.toLowerCase().includes(term) ||
      d.orderNumber.toLowerCase().includes(term) ||
      d.master.toLowerCase().includes(term) ||
      d.item.toLowerCase().includes(term) ||
      d.orderDate.toLowerCase().includes(term) ||
      d.deliveryDate.toLowerCase().includes(term) ||
      d.reason.toLowerCase().includes(term) ||
      d.row.toString().includes(term)
    );
  }, [duplicateList, searchTerm]);

  const hasDuplicates = duplicateList.length > 0;

  return (
    <ModalPortal>
      <div style={{
        position: 'fixed', inset: 0, background: 'rgba(15, 23, 42, 0.65)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 9999, backdropFilter: 'blur(6px)', padding: '1rem',
        overflowY: 'auto'
      }}>
        <div className="auth-card" style={{
          width: '100%',
          maxWidth: hasDuplicates ? '1080px' : '540px',
          maxHeight: '92vh',
          display: 'flex',
          flexDirection: 'column',
          position: 'relative',
          transition: 'max-width 0.3s ease',
          padding: hasDuplicates ? '1.75rem 2rem' : '2.25rem',
          margin: 'auto'
        }}>
          {/* Close button */}
          <button
            onClick={onClose}
            style={{
              position: 'absolute', top: '1.25rem', right: '1.25rem',
              color: 'var(--text-secondary)', background: 'transparent',
              border: 'none', cursor: 'pointer', zIndex: 10
            }}
          >
            <svg width="24" height="24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>

          <h2 style={{ fontSize: '1.4rem', fontWeight: 800, marginBottom: '0.35rem', color: 'var(--primary-color)' }}>
            Subir Órdenes (Excel)
          </h2>
          <p style={{ color: 'var(--text-secondary)', marginBottom: '1.25rem', fontSize: '0.85rem' }}>
            Acepta formatos <strong>FedEx</strong> y <strong>UPS</strong> — se detecta automáticamente.
          </p>

          {/* Si NO hay duplicados, mostrar la zona normal de carga */}
          {!hasDuplicates && (
            <>
              {/* Format indicators */}
              <div style={{ display: 'flex', gap: '0.75rem', marginBottom: '1.25rem', flexWrap: 'wrap' }}>
                <div style={{ padding: '0.4rem 0.9rem', borderRadius: '2rem', background: 'rgba(28,82,54,0.08)', border: '1px solid rgba(28,82,54,0.2)', fontSize: '0.78rem', color: 'var(--primary-color)', fontWeight: 600 }}>
                  ✈️ FedEx
                </div>
                <div style={{ padding: '0.4rem 0.9rem', borderRadius: '2rem', background: 'rgba(100,116,139,0.08)', border: '1px solid rgba(100,116,139,0.2)', fontSize: '0.78rem', color: '#475569', fontWeight: 600 }}>
                  📦 UPS
                </div>
              </div>

              <div style={{ marginBottom: '1.25rem' }}>
                <label style={{ display: 'block', fontSize: '0.85rem', fontWeight: 600, color: 'var(--text-primary)', marginBottom: '0.5rem' }}>
                  Courier (Para cálculo de fecha de envío)
                </label>
                <select 
                  className="input-field" 
                  style={{ width: '100%' }}
                  value={forcedFormat}
                  onChange={(e) => setForcedFormat(e.target.value as FormatType | 'auto')}
                >
                  <option value="auto">Detección Automática (Recomendado)</option>
                  <option value="ups">Forzar UPS</option>
                  <option value="fedex">Forzar FedEx</option>
                </select>
              </div>

              <div
                onDragOver={(e) => { e.preventDefault(); setDragActive(true); }}
                onDragLeave={() => setDragActive(false)}
                onDrop={handleDrop}
                onClick={() => fileInputRef.current?.click()}
                style={{
                  border: `2px dashed ${dragActive ? 'var(--primary-color)' : 'var(--border-color)'}`,
                  borderRadius: 'var(--radius-lg)',
                  padding: '3rem 2rem',
                  textAlign: 'center',
                  cursor: 'pointer',
                  backgroundColor: dragActive ? 'rgba(28, 82, 54, 0.05)' : 'rgba(255,255,255,0.5)',
                  transition: 'var(--transition)'
                }}
              >
                <input
                  type="file"
                  accept=".xlsx, .xls, .csv"
                  ref={fileInputRef}
                  onChange={(e) => e.target.files && processFile(e.target.files[0])}
                  style={{ display: 'none' }}
                />
                <svg width="48" height="48" fill="none" stroke="var(--primary-color)" style={{ margin: '0 auto 1rem', opacity: 0.8 }} viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                </svg>
                <p style={{ color: 'var(--text-primary)', fontWeight: 600 }}>Haz clic o arrastra el archivo aquí</p>
                <p style={{ color: 'var(--text-secondary)', fontSize: '0.8rem', marginTop: '0.5rem' }}>Soporta .XLSX, .XLS o .CSV</p>
              </div>

              {detectedFormat && (
                <div style={{ marginTop: '1rem', padding: '0.75rem 1rem', background: 'rgba(28,82,54,0.08)', borderRadius: 'var(--radius-md)', fontSize: '0.85rem', color: 'var(--primary-color)', fontWeight: 600 }}>
                  {formatLabel(detectedFormat)}
                </div>
              )}
            </>
          )}

          {loading && (
            <div style={{ marginTop: '1.5rem', textAlign: 'center', color: 'var(--primary-color)' }}>
              <div className="loading-spinner" style={{ margin: '0 auto 10px' }}></div>
              Procesando y validando órdenes...
            </div>
          )}

          {/* Error general cuando NO es lista de duplicados */}
          {error && !hasDuplicates && (
            <div style={{
              marginTop: '1.5rem',
              padding: '1rem',
              background: '#fef2f2',
              color: '#b91c1c',
              border: '1px solid #fca5a5',
              borderRadius: 'var(--radius-md)',
              fontSize: '0.85rem',
              whiteSpace: 'pre-line',
              lineHeight: 1.5
            }}>
              {error}
            </div>
          )}

          {/* ── TABLA INTERACTIVA DE ÓRDENES DUPLICADAS ── */}
          {hasDuplicates && (
            <div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, marginTop: '0.5rem' }}>
              {/* Alerta encabezado */}
              <div style={{
                background: '#fff1f2',
                border: '1px solid #fecdd3',
                borderRadius: '10px',
                padding: '1rem 1.25rem',
                marginBottom: '1rem'
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '0.5rem' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                    <span style={{ fontSize: '1.4rem' }}>⚠️</span>
                    <div>
                      <h4 style={{ margin: 0, fontSize: '0.95rem', fontWeight: 800, color: '#9f1239' }}>
                        {duplicateList.length} Líneas Duplicadas Detectadas
                      </h4>
                      <p style={{ margin: '0.2rem 0 0', fontSize: '0.8rem', color: '#be123c', lineHeight: 1.4 }}>
                        No se guardó ninguna orden para evitar duplicidad. Todas estas líneas coinciden en las 6 premisas (Cliente Master, Fecha Orden, PO, Order Number, Fecha Entrega, Item Number).
                      </p>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: '0.5rem', marginLeft: 'auto' }}>
                    <button
                      onClick={exportDuplicatesCSV}
                      className="btn-primary"
                      style={{
                        padding: '0.45rem 0.9rem', fontSize: '0.8rem',
                        background: '#059669', borderColor: '#059669',
                        boxShadow: 'none'
                      }}
                      title="Descargar listado en Excel / CSV"
                    >
                      📥 Descargar CSV ({duplicateList.length})
                    </button>
                    <button
                      onClick={() => {
                        setDuplicateList([]);
                        setError(null);
                      }}
                      className="btn-secondary"
                      style={{ padding: '0.45rem 0.9rem', fontSize: '0.8rem' }}
                    >
                      🔄 Probar Otro Archivo
                    </button>
                  </div>
                </div>
              </div>

              {/* Filtro de búsqueda en vivo */}
              <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginBottom: '0.75rem' }}>
                <div style={{ flex: 1, position: 'relative' }}>
                  <input
                    type="text"
                    placeholder="🔍 Buscar por PO, Order #, Master, Item, Fila o Fecha..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    style={{
                      padding: '0.5rem 0.85rem',
                      fontSize: '0.85rem',
                      borderRadius: '8px',
                      border: '1px solid #cbd5e1'
                    }}
                  />
                  {searchTerm && (
                    <button
                      onClick={() => setSearchTerm('')}
                      style={{
                        position: 'absolute', right: '10px', top: '50%', transform: 'translateY(-50%)',
                        background: 'none', border: 'none', color: '#94a3b8', cursor: 'pointer', fontSize: '0.9rem'
                      }}
                    >
                      ✕
                    </button>
                  )}
                </div>
                <span style={{ fontSize: '0.8rem', color: '#64748b', fontWeight: 600, whiteSpace: 'nowrap' }}>
                  Mostrando {filteredDuplicates.length} de {duplicateList.length}
                </span>
              </div>

              {/* Tabla scrolleable con cabecera fija */}
              <div style={{
                flex: 1,
                overflowY: 'auto',
                maxHeight: '420px',
                border: '1px solid #e2e8f0',
                borderRadius: '10px',
                background: '#ffffff',
                boxShadow: 'inset 0 2px 4px rgba(0,0,0,0.03)'
              }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: '0.8rem' }}>
                  <thead style={{ position: 'sticky', top: 0, zIndex: 5 }}>
                    <tr style={{ background: '#f8fafc', borderBottom: '2px solid #e2e8f0', color: '#334155' }}>
                      <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800, width: '60px' }}># Fila</th>
                      <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>PO</th>
                      <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>CUSTnbr (Order #)</th>
                      <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Cliente Master</th>
                      <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Fecha Orden</th>
                      <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Fecha Entrega</th>
                      <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Item</th>
                      <th style={{ padding: '0.65rem 0.75rem', fontWeight: 800 }}>Estado / Motivo</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredDuplicates.map((d, index) => {
                      const isRegistered = d.reason.includes('sistema');
                      return (
                        <tr
                          key={`${d.row}-${index}`}
                          style={{
                            borderBottom: '1px solid #f1f5f9',
                            backgroundColor: index % 2 === 0 ? '#ffffff' : '#fafafa',
                            transition: 'background-color 0.15s'
                          }}
                        >
                          <td style={{ padding: '0.6rem 0.75rem', fontWeight: 700, color: '#64748b' }}>
                            {d.row}
                          </td>
                          <td style={{ padding: '0.6rem 0.75rem', fontWeight: 700, color: '#1e293b' }}>
                            {d.po}
                          </td>
                          <td style={{ padding: '0.6rem 0.75rem', fontWeight: 600, color: '#0f172a' }}>
                            {d.orderNumber}
                          </td>
                          <td style={{ padding: '0.6rem 0.75rem', color: '#334155' }}>
                            {d.master}
                          </td>
                          <td style={{ padding: '0.6rem 0.75rem', color: '#475569', fontFamily: 'monospace', fontSize: '0.78rem' }}>
                            {d.orderDate}
                          </td>
                          <td style={{ padding: '0.6rem 0.75rem', color: '#475569', fontFamily: 'monospace', fontSize: '0.78rem' }}>
                            {d.deliveryDate}
                          </td>
                          <td style={{ padding: '0.6rem 0.75rem' }}>
                            <span style={{
                              background: '#eff6ff',
                              color: '#1d4ed8',
                              border: '1px solid #bfdbfe',
                              borderRadius: '4px',
                              padding: '0.2rem 0.5rem',
                              fontFamily: 'monospace',
                              fontWeight: 700,
                              fontSize: '0.75rem'
                            }}>
                              {d.item}
                            </span>
                          </td>
                          <td style={{ padding: '0.6rem 0.75rem' }}>
                            <span style={{
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: '0.3rem',
                              padding: '0.25rem 0.6rem',
                              borderRadius: '999px',
                              fontSize: '0.72rem',
                              fontWeight: 700,
                              background: isRegistered ? '#fee2e2' : '#fef3c7',
                              color: isRegistered ? '#991b1b' : '#92400e',
                              border: `1px solid ${isRegistered ? '#fca5a5' : '#fde68a'}`
                            }}>
                              {isRegistered ? '🔴 Ya en Sistema' : '🟠 Repetido en Archivo'}
                            </span>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              <div style={{ marginTop: '1rem', display: 'flex', justifyContent: 'flex-end', gap: '0.75rem' }}>
                <button
                  className="btn-secondary"
                  onClick={onClose}
                  style={{ padding: '0.55rem 1.5rem', fontSize: '0.85rem' }}
                >
                  Cerrar
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </ModalPortal>
  );
}
