'use client';

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

export default function TrackingUploadModal({ onClose, onUploadSuccess }: { onClose: () => void, onUploadSuccess: (res: any) => void }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const processFile = async (file: File) => {
    setLoading(true);
    setError(null);
    try {
      const data = await file.arrayBuffer();
      const workbook = XLSX.read(data);
      const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
      const jsonData = XLSX.utils.sheet_to_json(firstSheet);

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

      const responseData = await res.json();
      if (!res.ok) throw new Error(responseData.error || 'Error al procesar archivo');

      onUploadSuccess(responseData);
      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]);
    }
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, backdropFilter: 'blur(4px)' }}>
      <div className="auth-card" style={{ width: '100%', maxWidth: '500px', position: 'relative' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: '1rem', right: '1rem', color: 'var(--text-secondary)' }}>
          <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.5rem', marginBottom: '1rem', color: 'var(--primary-color)' }}>Subir Respuesta de FedEx/UPS</h2>
        <p style={{ color: 'var(--text-secondary)', marginBottom: '1.5rem', fontSize: '0.9rem' }}>
          Sube el archivo CSV o Excel generado por FedEx con los tracking numbers. El sistema asignará el tracking a cada caja validando PO, Order Number y Producto.
        </p>
        
        <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>

        {loading && <div style={{ marginTop: '1.5rem', textAlign: 'center', color: 'var(--primary-color)' }}><div className="loading-spinner" style={{ margin: '0 auto 10px' }}></div>Procesando...</div>}
        {error && <div style={{ marginTop: '1.5rem', padding: '1rem', background: '#fef2f2', color: 'var(--danger-color)', borderRadius: 'var(--radius-md)', fontSize: '0.9rem' }}>{error}</div>}
      </div>
    </div>
  );
}
