import React, { useState, useRef, useCallback } from 'react';

// ─── Template CSV columns ───────────────────────────────────────────────────
const TEMPLATE_HEADERS = [
  'wbsCode', 'phase', 'title', 'status', 'priority',
  'assignee', 'dueDate', 'estimatedHours', 'plannedCost', 'progressPct',
];

const TEMPLATE_EXAMPLE = [
  '1.1', 'Fase 1 — Planificación', 'Levantamiento de requerimientos',
  'EN_PROGRESO', 'ALTO', 'Ana García', '2026-08-15', '40', '6000', '50',
];

const STATUS_OPTIONS   = ['PENDIENTE','EN_PROGRESO','COMPLETADA','BLOQUEADA','CANCELADA'];
const PRIORITY_OPTIONS = ['CRITICO','ALTO','MEDIO','BAJO'];

// ─── Parse CSV text → array of objects ─────────────────────────────────────
function parseCSV(text) {
  const lines = text.trim().split(/\r?\n/).filter(Boolean);
  if (lines.length < 2) return { headers: [], rows: [], error: 'El archivo está vacío o solo tiene encabezados.' };

  const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g, ''));
  const rows = lines.slice(1).map((line, idx) => {
    // Handle quoted fields with commas inside
    const values = [];
    let current = '';
    let inQuotes = false;
    for (const ch of line) {
      if (ch === '"') { inQuotes = !inQuotes; continue; }
      if (ch === ',' && !inQuotes) { values.push(current.trim()); current = ''; continue; }
      current += ch;
    }
    values.push(current.trim());

    const obj = { _row: idx + 2 };
    headers.forEach((h, i) => { obj[h] = values[i] ?? ''; });
    return obj;
  });

  return { headers, rows, error: null };
}

// ─── Validate a single row ──────────────────────────────────────────────────
function validateRow(row) {
  const errors = [];
  if (!row.title?.trim())       errors.push('title es requerido');
  if (!row.phase?.trim())       errors.push('phase es requerido');
  if (row.status && !STATUS_OPTIONS.includes(row.status))
    errors.push(`status inválido: "${row.status}"`);
  if (row.priority && !PRIORITY_OPTIONS.includes(row.priority))
    errors.push(`priority inválido: "${row.priority}"`);
  if (row.dueDate && isNaN(Date.parse(row.dueDate)))
    errors.push(`dueDate inválido: "${row.dueDate}"`);
  const hrs = parseFloat(row.estimatedHours);
  if (row.estimatedHours && (isNaN(hrs) || hrs < 0))
    errors.push('estimatedHours debe ser número ≥ 0');
  const cost = parseFloat(row.plannedCost);
  if (row.plannedCost && (isNaN(cost) || cost < 0))
    errors.push('plannedCost debe ser número ≥ 0');
  const pct = parseFloat(row.progressPct);
  if (row.progressPct && (isNaN(pct) || pct < 0 || pct > 100))
    errors.push('progressPct debe ser 0-100');
  return errors;
}

// ─── Convert raw row → task object ─────────────────────────────────────────
function rowToTask(row, idx) {
  return {
    id: `imported_${Date.now()}_${idx}`,
    wbsCode: row.wbsCode || `${idx + 1}`,
    phase: row.phase?.trim() || 'Sin fase',
    title: row.title?.trim() || '(sin título)',
    status: STATUS_OPTIONS.includes(row.status) ? row.status : 'PENDIENTE',
    priority: PRIORITY_OPTIONS.includes(row.priority) ? row.priority : 'MEDIO',
    assignee: row.assignee?.trim() ? { nombre: row.assignee.trim() } : null,
    dueDate: row.dueDate?.trim() || null,
    estimatedHours: parseFloat(row.estimatedHours) || 0,
    plannedCost: parseFloat(row.plannedCost) || 0,
    progressPct: Math.min(100, Math.max(0, parseFloat(row.progressPct) || 0)),
    actualHours: 0,
    actualCost: 0,
    predecessors: [],
    isMilestone: false,
    isCritical: row.priority === 'CRITICO',
    baselineStart: null,
    baselineEnd: null,
  };
}

// ─── Download template CSV ──────────────────────────────────────────────────
function downloadTemplate() {
  const lines = [TEMPLATE_HEADERS.join(','), TEMPLATE_EXAMPLE.join(',')];
  const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = 'plantilla_tareas.csv'; a.click();
  URL.revokeObjectURL(url);
}

// ── STATUS badge colors ──────────────────────────────────────────────────────
const STATUS_COLORS = {
  COMPLETADA:   'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400',
  EN_PROGRESO:  'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400',
  PENDIENTE:    'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300',
  BLOQUEADA:    'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400',
  CANCELADA:    'bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400',
};
const PRIORITY_COLORS = {
  CRITICO: 'text-red-600 dark:text-red-400',
  ALTO:    'text-orange-600 dark:text-orange-400',
  MEDIO:   'text-blue-600 dark:text-blue-400',
  BAJO:    'text-slate-500 dark:text-slate-400',
};

// ─── STEP indicators ────────────────────────────────────────────────────────
function StepDot({ n, label, active, done }) {
  return (
    <div className="flex flex-col items-center gap-1">
      <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold border-2 transition-colors
        ${done  ? 'bg-emerald-500 border-emerald-500 text-white'
        : active ? 'bg-blue-600 border-blue-600 text-white'
        :          'bg-white dark:bg-slate-800 border-slate-300 dark:border-slate-600 text-slate-400'}`}>
        {done ? '✓' : n}
      </div>
      <span className={`text-xs font-medium ${active || done ? 'text-slate-700 dark:text-slate-200' : 'text-slate-400 dark:text-slate-500'}`}>
        {label}
      </span>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// MAIN COMPONENT
// ═══════════════════════════════════════════════════════════════════════════
export default function CSVImportModal({ onClose, onImport, projectName = '' }) {
  const [step, setStep]         = useState(1); // 1=Upload 2=Preview 3=Done
  const [dragging, setDragging] = useState(false);
  const [fileName, setFileName] = useState('');
  const [parsed, setParsed]     = useState(null);   // { headers, rows, error }
  const [validated, setValidated] = useState([]);   // rows with _errors
  const [selected, setSelected] = useState(new Set()); // selected row indices
  const fileRef = useRef();

  // ── Process file ─────────────────────────────────────────────────────────
  const processFile = useCallback((file) => {
    if (!file) return;
    if (!file.name.match(/\.(csv|txt)$/i)) {
      setParsed({ headers: [], rows: [], error: 'Solo se aceptan archivos .csv — exporta tu Excel como CSV primero.' });
      return;
    }
    setFileName(file.name);
    const reader = new FileReader();
    reader.onload = (e) => {
      const result = parseCSV(e.target.result);
      if (result.error) { setParsed(result); return; }
      const withErrors = result.rows.map(r => ({ ...r, _errors: validateRow(r) }));
      setParsed(result);
      setValidated(withErrors);
      setSelected(new Set(withErrors.map((_, i) => i)));
      setStep(2);
    };
    reader.readAsText(file, 'UTF-8');
  }, []);

  const handleDrop = useCallback((e) => {
    e.preventDefault(); setDragging(false);
    processFile(e.dataTransfer.files[0]);
  }, [processFile]);

  const toggleRow = (i) => {
    setSelected(prev => {
      const next = new Set(prev);
      next.has(i) ? next.delete(i) : next.add(i);
      return next;
    });
  };
  const toggleAll = () => {
    setSelected(prev => prev.size === validated.length ? new Set() : new Set(validated.map((_, i) => i)));
  };

  const validCount   = validated.filter((r, i) => selected.has(i) && r._errors.length === 0).length;
  const warningCount = validated.filter((r, i) => selected.has(i) && r._errors.length > 0).length;

  const handleImport = () => {
    const tasks = validated
      .filter((r, i) => selected.has(i) && r._errors.length === 0)
      .map((r, i) => rowToTask(r, i));
    onImport(tasks);
    setStep(3);
  };

  // ── STEP 1 — Upload ───────────────────────────────────────────────────────
  const renderUpload = () => (
    <div className="space-y-5">
      {/* Instructions */}
      <div className="bg-blue-50 dark:bg-blue-500/10 border border-blue-200 dark:border-blue-500/30 rounded-xl p-4">
        <p className="text-sm font-semibold text-blue-700 dark:text-blue-400 mb-2">¿Tienes las tareas en Excel?</p>
        <ol className="text-sm text-blue-600 dark:text-blue-300 space-y-1 list-decimal list-inside">
          <li>Descarga la plantilla CSV de abajo</li>
          <li>Llénala en Excel (o Google Sheets)</li>
          <li>Guarda como <strong>CSV (UTF-8)</strong></li>
          <li>Sube el archivo aquí</li>
        </ol>
      </div>

      {/* Download template */}
      <button onClick={downloadTemplate}
        className="w-full flex items-center gap-3 px-4 py-3 border-2 border-dashed border-slate-300 dark:border-slate-600 rounded-xl text-sm text-slate-600 dark:text-slate-300 hover:border-blue-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors cursor-pointer">
        <svg className="w-5 h-5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M12 10v6m0 0l-3-3m3 3l3-3M3 17V7a2 2 0 012-2h6l2 2h6a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z"/>
        </svg>
        <div className="text-left">
          <p className="font-semibold">Descargar plantilla CSV</p>
          <p className="text-xs text-slate-400 dark:text-slate-500">plantilla_tareas.csv — con columnas y ejemplo</p>
        </div>
      </button>

      {/* Column guide */}
      <div className="rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden text-xs">
        <div className="bg-slate-50 dark:bg-slate-800 px-3 py-2 font-semibold text-slate-600 dark:text-slate-300 border-b border-slate-200 dark:border-slate-700">
          Columnas soportadas
        </div>
        <div className="divide-y divide-slate-100 dark:divide-slate-700">
          {[
            ['wbsCode',        'Código WBS', '1.1, 1.2…', false],
            ['phase',          'Fase / Entregable', 'Fase 1 — Diseño', true],
            ['title',          'Nombre de la tarea', '', true],
            ['status',         'Estado', 'PENDIENTE | EN_PROGRESO | COMPLETADA | BLOQUEADA', false],
            ['priority',       'Prioridad', 'CRITICO | ALTO | MEDIO | BAJO', false],
            ['assignee',       'Responsable', 'Nombre del miembro del equipo', false],
            ['dueDate',        'Fecha límite', 'AAAA-MM-DD', false],
            ['estimatedHours', 'Horas estimadas', 'número', false],
            ['plannedCost',    'Costo planificado $', 'número', false],
            ['progressPct',    '% avance', '0 a 100', false],
          ].map(([col, desc, example, req]) => (
            <div key={col} className="grid grid-cols-3 px-3 py-1.5 gap-2">
              <span className="font-mono text-blue-600 dark:text-blue-400">{col}{req && <span className="text-red-500 ml-0.5">*</span>}</span>
              <span className="text-slate-600 dark:text-slate-300">{desc}</span>
              <span className="text-slate-400 dark:text-slate-500">{example}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Drop zone */}
      <div
        onDragOver={e => { e.preventDefault(); setDragging(true); }}
        onDragLeave={() => setDragging(false)}
        onDrop={handleDrop}
        onClick={() => fileRef.current?.click()}
        className={`relative flex flex-col items-center justify-center gap-3 px-6 py-10 border-2 border-dashed rounded-2xl cursor-pointer transition-all
          ${dragging ? 'border-blue-500 bg-blue-50 dark:bg-blue-500/10' : 'border-slate-300 dark:border-slate-600 hover:border-blue-400 hover:bg-slate-50 dark:hover:bg-slate-800'}`}>
        <svg className={`w-10 h-10 transition-colors ${dragging ? 'text-blue-500' : 'text-slate-400'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 13h6m-3-3v6m5 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
        </svg>
        <div className="text-center">
          <p className="font-semibold text-slate-700 dark:text-slate-200">Arrastra tu archivo CSV aquí</p>
          <p className="text-sm text-slate-400 dark:text-slate-500 mt-0.5">o haz clic para buscar</p>
        </div>
        <input ref={fileRef} type="file" accept=".csv,.txt" className="hidden"
          onChange={e => processFile(e.target.files[0])} />
      </div>

      {parsed?.error && (
        <div className="bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/30 rounded-xl p-3 text-sm text-red-700 dark:text-red-400">
          ⚠️ {parsed.error}
        </div>
      )}
    </div>
  );

  // ── STEP 2 — Preview ──────────────────────────────────────────────────────
  const renderPreview = () => (
    <div className="space-y-4">
      {/* Summary bar */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="flex items-center gap-2 text-sm text-slate-500 dark:text-slate-400">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
          </svg>
          <span className="font-medium text-slate-700 dark:text-slate-200">{fileName}</span>
        </div>
        <span className="text-slate-300 dark:text-slate-600">|</span>
        <span className="text-sm text-slate-500 dark:text-slate-400">{validated.length} filas detectadas</span>
        <span className="text-emerald-600 dark:text-emerald-400 text-sm font-medium">{validCount} válidas</span>
        {warningCount > 0 && <span className="text-red-600 dark:text-red-400 text-sm font-medium">{warningCount} con errores</span>}
        <button onClick={() => { setParsed(null); setValidated([]); setStep(1); }}
          className="ml-auto text-xs text-blue-600 dark:text-blue-400 hover:underline cursor-pointer">
          ← Cambiar archivo
        </button>
      </div>

      {/* Table */}
      <div className="border border-slate-200 dark:border-slate-700 rounded-xl overflow-hidden max-h-80 overflow-y-auto">
        <table className="w-full text-xs">
          <thead className="bg-slate-50 dark:bg-slate-800 sticky top-0">
            <tr>
              <th className="px-3 py-2 text-left">
                <input type="checkbox"
                  checked={selected.size === validated.length && validated.length > 0}
                  onChange={toggleAll}
                  className="cursor-pointer" />
              </th>
              <th className="px-3 py-2 text-left text-slate-500 dark:text-slate-400 font-medium">#</th>
              <th className="px-3 py-2 text-left text-slate-500 dark:text-slate-400 font-medium">WBS</th>
              <th className="px-3 py-2 text-left text-slate-500 dark:text-slate-400 font-medium">Tarea</th>
              <th className="px-3 py-2 text-left text-slate-500 dark:text-slate-400 font-medium">Fase</th>
              <th className="px-3 py-2 text-left text-slate-500 dark:text-slate-400 font-medium">Estado</th>
              <th className="px-3 py-2 text-left text-slate-500 dark:text-slate-400 font-medium">Prioridad</th>
              <th className="px-3 py-2 text-left text-slate-500 dark:text-slate-400 font-medium">Responsable</th>
              <th className="px-3 py-2 text-left text-slate-500 dark:text-slate-400 font-medium">Validación</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100 dark:divide-slate-700">
            {validated.map((row, i) => (
              <tr key={i}
                className={`transition-colors cursor-pointer
                  ${!selected.has(i) ? 'opacity-40' : ''}
                  ${row._errors.length > 0 ? 'bg-red-50 dark:bg-red-500/5' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'}`}
                onClick={() => toggleRow(i)}>
                <td className="px-3 py-2">
                  <input type="checkbox" checked={selected.has(i)} onChange={() => toggleRow(i)}
                    onClick={e => e.stopPropagation()} className="cursor-pointer" />
                </td>
                <td className="px-3 py-2 text-slate-400 dark:text-slate-500">{row._row}</td>
                <td className="px-3 py-2 font-mono text-slate-600 dark:text-slate-300">{row.wbsCode || '—'}</td>
                <td className="px-3 py-2 font-medium text-slate-800 dark:text-slate-100 max-w-[160px] truncate">{row.title || '(vacío)'}</td>
                <td className="px-3 py-2 text-slate-500 dark:text-slate-400 max-w-[120px] truncate">{row.phase || '—'}</td>
                <td className="px-3 py-2">
                  {row.status ? (
                    <span className={`px-1.5 py-0.5 rounded-full font-medium ${STATUS_COLORS[row.status] || 'bg-slate-100 text-slate-600'}`}>
                      {row.status}
                    </span>
                  ) : <span className="text-slate-400 dark:text-slate-500">—</span>}
                </td>
                <td className={`px-3 py-2 font-semibold ${PRIORITY_COLORS[row.priority] || 'text-slate-400'}`}>
                  {row.priority || '—'}
                </td>
                <td className="px-3 py-2 text-slate-600 dark:text-slate-300">{row.assignee || '—'}</td>
                <td className="px-3 py-2">
                  {row._errors.length === 0
                    ? <span className="text-emerald-600 dark:text-emerald-400 font-medium">✓ OK</span>
                    : <span className="text-red-600 dark:text-red-400" title={row._errors.join(', ')}>
                        ⚠ {row._errors[0]}{row._errors.length > 1 ? ` (+${row._errors.length - 1})` : ''}
                      </span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {warningCount > 0 && (
        <p className="text-xs text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/30 rounded-lg px-3 py-2">
          Las filas con errores serán omitidas al importar. Corrígelas en tu archivo y vuelve a cargarlo para incluirlas.
        </p>
      )}
    </div>
  );

  // ── STEP 3 — Done ─────────────────────────────────────────────────────────
  const renderDone = () => (
    <div className="flex flex-col items-center justify-center py-10 gap-4 text-center">
      <div className="w-16 h-16 rounded-full bg-emerald-100 dark:bg-emerald-500/20 flex items-center justify-center">
        <svg className="w-8 h-8 text-emerald-600 dark:text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/>
        </svg>
      </div>
      <div>
        <p className="text-lg font-bold text-slate-800 dark:text-slate-100">¡Importación exitosa!</p>
        <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">
          {validCount} tarea{validCount !== 1 ? 's' : ''} agregada{validCount !== 1 ? 's' : ''} al proyecto {projectName && `"${projectName}"`}
        </p>
      </div>
      <button onClick={onClose}
        className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-xl transition cursor-pointer">
        Ver en WBS
      </button>
    </div>
  );

  // ── MODAL SHELL ───────────────────────────────────────────────────────────
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
      <div className="bg-white dark:bg-slate-900 rounded-2xl shadow-2xl border border-slate-200 dark:border-slate-700 w-full max-w-3xl flex flex-col max-h-[90vh]">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 dark:border-slate-700 shrink-0">
          <div>
            <h2 className="font-bold text-slate-900 dark:text-white text-lg">Importar tareas desde CSV / Excel</h2>
            {projectName && <p className="text-xs text-slate-400 dark:text-slate-500 mt-0.5">Proyecto: {projectName}</p>}
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center rounded-lg text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/>
            </svg>
          </button>
        </div>

        {/* Steps */}
        {step < 3 && (
          <div className="flex items-center justify-center gap-6 px-6 py-4 border-b border-slate-100 dark:border-slate-800 shrink-0">
            <StepDot n={1} label="Subir archivo" active={step === 1} done={step > 1} />
            <div className="flex-1 h-px bg-slate-200 dark:bg-slate-700 max-w-[80px]" />
            <StepDot n={2} label="Previsualizar" active={step === 2} done={step > 2} />
            <div className="flex-1 h-px bg-slate-200 dark:bg-slate-700 max-w-[80px]" />
            <StepDot n={3} label="Confirmar" active={step === 3} done={false} />
          </div>
        )}

        {/* Body */}
        <div className="overflow-y-auto px-6 py-5 flex-1">
          {step === 1 && renderUpload()}
          {step === 2 && renderPreview()}
          {step === 3 && renderDone()}
        </div>

        {/* Footer */}
        {step === 2 && (
          <div className="flex items-center justify-between px-6 py-4 border-t border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50 shrink-0 rounded-b-2xl">
            <p className="text-sm text-slate-500 dark:text-slate-400">
              <span className="font-semibold text-slate-700 dark:text-slate-200">{selected.size}</span> filas seleccionadas
              · <span className="font-semibold text-emerald-600 dark:text-emerald-400">{validCount}</span> se importarán
            </p>
            <div className="flex gap-2">
              <button onClick={onClose}
                className="px-4 py-2 text-sm text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 rounded-xl transition cursor-pointer">
                Cancelar
              </button>
              <button onClick={handleImport} disabled={validCount === 0}
                className="px-5 py-2 text-sm font-semibold bg-blue-600 hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed text-white rounded-xl transition cursor-pointer">
                Importar {validCount} tarea{validCount !== 1 ? 's' : ''}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
