import React, { useState } from 'react';
import ModalPortal from '@/components/common/ModalPortal';

type Props = {
  onClose: () => void;
  onSuccess: () => void;
};

export default function MassTrackingModal({ onClose, onSuccess }: Props) {
  const [data, setData] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [result, setResult] = useState<{ updated: number, notFound: string[] } | null>(null);

  const handleProcess = async () => {
    if (!data.trim()) { setError('Por favor pega los datos (PO y Tracking)'); return; }
    setLoading(true); setError(''); setResult(null);

    const lines = data.split('\n').map(l => l.trim()).filter(l => l);
    const mappings: { po: string; tracking: string }[] = [];

    for (const line of lines) {
      // Intentar dividir por tabulación (desde excel) o coma
      const parts = line.split(/\t|,/);
      if (parts.length >= 2) {
        mappings.push({ po: parts[0].trim(), tracking: parts[1].trim() });
      } else {
        // Si no hay tab/coma, buscar el primer espacio grande
        const match = line.match(/^([^\s]+)\s+(.+)$/);
        if (match) {
          mappings.push({ po: match[1].trim(), tracking: match[2].trim() });
        }
      }
    }

    if (mappings.length === 0) {
      setError('No se pudo interpretar los datos. Asegúrate de tener formato: PO [tab] Tracking');
      setLoading(false);
      return;
    }

    try {
      const res = await fetch('/api/orders/mass-tracking', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mappings })
      });
      const resData = await res.json();
      if (!res.ok) throw new Error(resData.error || 'Error al procesar trackings');
      setResult(resData);
    } catch (err: any) {
      setError(err.message);
    }
    setLoading(false);
  };

  return (
    <ModalPortal>
      <div style={{ position: 'fixed', inset: 0, zIndex: 9999, 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' }}>
        <h2 style={{ fontSize: '1.25rem', fontWeight: 700, marginBottom: '0.5rem', color: 'var(--primary-color)' }}>Asignación Masiva de Trackings</h2>
        <p style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', marginBottom: '1.5rem' }}>
          Pega directamente desde Excel las columnas <strong>PO</strong> y <strong>Tracking Number</strong>.
        </p>

        {!result ? (
          <>
            <textarea
              className="input-field"
              rows={10}
              placeholder="Ejemplo:&#10;PO-1001&#9;1Z999999999&#10;PO-1002&#9;1Z888888888"
              value={data}
              onChange={e => setData(e.target.value)}
              style={{ width: '100%', fontFamily: 'monospace', fontSize: '0.85rem', marginBottom: '1rem' }}
            />
            
            {error && <div style={{ padding: '0.75rem', background: '#fef2f2', color: '#dc2626', borderRadius: '8px', fontSize: '0.875rem', marginBottom: '1rem' }}>{error}</div>}

            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem' }}>
              <button className="btn-secondary" onClick={onClose} disabled={loading}>Cancelar</button>
              <button className="btn-primary" onClick={handleProcess} disabled={loading}>
                {loading ? 'Procesando...' : 'Asignar Trackings'}
              </button>
            </div>
          </>
        ) : (
          <div>
            <div style={{ padding: '1rem', background: '#ecfdf5', color: '#059669', borderRadius: '8px', marginBottom: '1rem', fontWeight: 600 }}>
              ✓ Se actualizaron {result.updated} líneas de órdenes exitosamente.
            </div>
            
            {result.notFound.length > 0 && (
              <div style={{ padding: '1rem', background: '#fffbeb', color: '#b45309', borderRadius: '8px', marginBottom: '1rem' }}>
                <p style={{ fontWeight: 600, marginBottom: '0.5rem' }}>⚠️ POs no encontrados o ya asignados:</p>
                <ul style={{ margin: 0, paddingLeft: '1.5rem', fontSize: '0.85rem' }}>
                  {result.notFound.map((po, i) => <li key={i}>{po}</li>)}
                </ul>
              </div>
            )}

            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <button className="btn-primary" onClick={() => { onSuccess(); onClose(); }}>Cerrar y Refrescar</button>
            </div>
          </div>
        )}
      </div>
    </div>
    </ModalPortal>
  );
}
