import { useState, useMemo } from 'react';
import {
  BarChart, Bar, LineChart, Line, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer
} from 'recharts';
import { useProject } from '../../context/ProjectContext';
import { MOCK_PROJECTS } from '../../services/mockData';

// ── Mock Data ────────────────────────────────────────────────────────────────

const TEAM_MEMBERS = [
  { id: 'u1', name: 'Admin Sistema',   avatar: 'AS', role: 'Senior',  rate: 85, color: '#2563EB' },
  { id: 'u2', name: 'Paula Soto',      avatar: 'AT', role: 'Senior',  rate: 85, color: '#10B981' },
  { id: 'u3', name: 'Álvaro Romero',    avatar: 'LM', role: 'Mid',     rate: 55, color: '#8B5CF6' },
  { id: 'u4', name: 'María García',    avatar: 'MG', role: 'Mid',     rate: 55, color: '#F59E0B' },
  { id: 'u5', name: 'Carlos Ruiz',     avatar: 'CR', role: 'Junior',  rate: 35, color: '#EF4444' },
  { id: 'u6', name: 'Sofia Herrera',   avatar: 'SH', role: 'Junior',  rate: 35, color: '#06B6D4' },
];

const TASKS = [
  { id: 't1', code: 'TCN-001', name: 'Diseño arquitectura cimientos',      projectId: 'p4', billable: true  },
  { id: 't2', code: 'TCN-002', name: 'Supervisión estructura metálica',    projectId: 'p4', billable: true  },
  { id: 't3', code: 'MUS-001', name: 'Grabación pistas vocales',           projectId: 'p4', billable: true  },
  { id: 't4', code: 'MUS-002', name: 'Mezcla y masterización',             projectId: 'p4', billable: true  },
  { id: 't5', code: 'ERP-001', name: 'Análisis de requerimientos',         projectId: 'p4', billable: true  },
  { id: 't6', code: 'ERP-002', name: 'Desarrollo módulo financiero',       projectId: 'p4', billable: true  },
  { id: 't7', code: 'ERP-003', name: 'Integración APIs externas',          projectId: 'p4', billable: false },
  { id: 't8', code: 'AR-001',  name: 'Desarrollo frontend React',          projectId: 'p4', billable: true  },
  { id: 't9', code: 'AR-002',  name: 'Arquitectura backend Node.js',       projectId: 'p4', billable: true  },
  { id: 't10',code: 'AR-003',  name: 'Testing y QA',                       projectId: 'p4', billable: false },
];

// hours[userId][taskId][dayIndex] — dayIndex 0=Mon..6=Sun
const INITIAL_HOURS = {
  u1: { t8: [6,7,6,8,5,0,0], t9: [2,1,2,0,3,0,0] },
  u2: { t5: [7,8,8,9,8,0,0], t6: [0,0,0,1,0,0,0] },
  u3: { t5: [3,4,3,4,3,0,0], t6: [5,4,5,5,5,0,0], t7: [0,0,0,0,2,0,0] },
  u4: { t3: [6,6,6,6,6,0,0], t4: [2,2,2,2,2,0,0] },
  u5: { t1: [7,7,7,7,7,0,0], t10:[1,1,1,1,1,0,0] },
  u6: { t2: [4,5,4,5,4,0,0], t7: [3,3,3,3,3,0,0] },
};

const WEEK_LABELS = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'];

// 8 weeks of personal hours (for Mi Resumen line chart)
const WEEKLY_HISTORY = [
  { week: 'S-7', hours: 38 }, { week: 'S-6', hours: 42 }, { week: 'S-5', hours: 35 },
  { week: 'S-4', hours: 40 }, { week: 'S-3', hours: 44 }, { week: 'S-2', hours: 39 },
  { week: 'S-1', hours: 41 }, { week: 'S actual', hours: 39 },
];

// Team report data
const TEAM_REPORT = [
  { userId:'u1', projectId:'p4', thisWeek:39, thisMonth:158, ytd:620, billablePct:85, planned:40  },
  { userId:'u2', projectId:'p4', thisWeek:41, thisMonth:165, ytd:580, billablePct:90, planned:40  },
  { userId:'u3', projectId:'p4', thisWeek:42, thisMonth:170, ytd:610, billablePct:75, planned:40  },
  { userId:'u4', projectId:'p4', thisWeek:38, thisMonth:152, ytd:540, billablePct:80, planned:40  },
  { userId:'u5', projectId:'p4', thisWeek:40, thisMonth:160, ytd:490, billablePct:70, planned:40  },
  { userId:'u6', projectId:'p4', thisWeek:37, thisMonth:148, ytd:510, billablePct:72, planned:40  },
];

// Project planned vs actual per task (for Por Proyecto tab)
const PROJECT_TASK_DATA = {
  p1: [
    { task:'TCN-001', name:'Arq. cimientos',    assignee:'Carlos R.',  estimated:120, actual:88,  pct:73 },
    { task:'TCN-002', name:'Estructura metál.', assignee:'Sofía H.',   estimated:80,  actual:37,  pct:46 },
    { task:'TCN-003', name:'Instalaciones',     assignee:'Carlos R.',  estimated:60,  actual:12,  pct:20 },
  ],
  p2: [
    { task:'MUS-001', name:'Grabación vocal',   assignee:'María G.',   estimated:40,  actual:38,  pct:95 },
    { task:'MUS-002', name:'Mezcla',            assignee:'María G.',   estimated:30,  actual:28,  pct:93 },
    { task:'MUS-003', name:'Masterización',     assignee:'María G.',   estimated:10,  actual:4,   pct:40 },
  ],
  p3: [
    { task:'ERP-001', name:'Análisis req.',     assignee:'Ana T.',     estimated:80,  actual:99,  pct:100 },
    { task:'ERP-002', name:'Módulo financiero', assignee:'Luis M.',    estimated:120, actual:130, pct:85  },
    { task:'ERP-003', name:'Integración APIs',  assignee:'Luis M.',    estimated:60,  actual:70,  pct:70  },
    { task:'ERP-004', name:'Testing',           assignee:'Ana T.',     estimated:40,  actual:20,  pct:50  },
  ],
  p4: [
    { task:'AR-001',  name:'Frontend React',    assignee:'Admin S.',   estimated:100, actual:78,  pct:78 },
    { task:'AR-002',  name:'Backend Node',      assignee:'Admin S.',   estimated:80,  actual:61,  pct:76 },
    { task:'AR-003',  name:'Testing QA',        assignee:'Admin S.',   estimated:40,  actual:18,  pct:45 },
  ],
};

// ── Helpers ──────────────────────────────────────────────────────────────────

const getProject = (id) => MOCK_PROJECTS.find(p => p.id === id) || {};

const PROJECT_COLORS = { p1:'#3b82f6', p2:'#10b981', p3:'#ef4444', p4:'#8b5cf6' };

const statusColor = (thisWeek, planned) => {
  const ratio = thisWeek / planned;
  if (ratio <= 1.10) return 'text-emerald-600 dark:text-emerald-400';
  if (ratio <= 1.20) return 'text-amber-600 dark:text-amber-400';
  return 'text-red-600 dark:text-red-400';
};

const varianceColor = (estimated, actual) => {
  if (actual <= estimated) return 'text-emerald-600 dark:text-emerald-400';
  const over = (actual - estimated) / estimated;
  if (over <= 0.10) return 'text-amber-600 dark:text-amber-400';
  return 'text-red-600 dark:text-red-400';
};

// ── Sub-components ───────────────────────────────────────────────────────────

function KPICard({ label, value, sub, icon, accent = 'blue' }) {
  const accents = {
    blue:   'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400',
    green:  'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400',
    amber:  'bg-amber-50 dark:bg-amber-900/20 text-amber-600 dark:text-amber-400',
    purple: 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400',
  };
  return (
    <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
      <div className="flex items-start justify-between">
        <div>
          <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">{label}</p>
          <p className="text-2xl font-bold text-slate-900 dark:text-white mt-1">{value}</p>
          {sub && <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">{sub}</p>}
        </div>
        <div className={`w-10 h-10 rounded-xl flex items-center justify-center text-lg ${accents[accent]}`}>{icon}</div>
      </div>
    </div>
  );
}

// ── Tab 1: Registro de Horas ─────────────────────────────────────────────────

function RegistroHoras({ selectedProjectId }) {
  const [weekOffset, setWeekOffset] = useState(0);
  const [hours, setHours] = useState(INITIAL_HOURS);
  const [saved, setSaved] = useState(false);

  const currentUserId = 'u1';

  const filteredTasks = useMemo(() =>
    TASKS.filter(t => !selectedProjectId || t.projectId === selectedProjectId),
    [selectedProjectId]
  );

  const userHours = hours[currentUserId] || {};

  const dayTotals = WEEK_LABELS.map((_, di) =>
    filteredTasks.reduce((sum, t) => sum + (userHours[t.id]?.[di] || 0), 0)
  );
  const weekTotal = dayTotals.reduce((a, b) => a + b, 0);

  const hasOvertime = dayTotals.some(h => h > 9);

  const handleChange = (taskId, dayIdx, val) => {
    const num = Math.min(24, Math.max(0, Number(val) || 0));
    setSaved(false);
    setHours(prev => ({
      ...prev,
      [currentUserId]: {
        ...prev[currentUserId],
        [taskId]: prev[currentUserId]?.[taskId]
          ? prev[currentUserId][taskId].map((h, i) => i === dayIdx ? num : h)
          : WEEK_LABELS.map((_, i) => i === dayIdx ? num : 0),
      },
    }));
  };

  const weekLabel = weekOffset === 0 ? 'Semana actual'
    : weekOffset < 0 ? `Semana ${weekOffset}` : `Semana +${weekOffset}`;

  return (
    <div className="space-y-4">
      {/* Header controls */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <button
            onClick={() => setWeekOffset(w => w - 1)}
            className="border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 rounded-xl px-4 py-2.5 text-sm"
          >← Anterior</button>
          <span className="text-sm font-medium text-slate-700 dark:text-slate-300 px-2">{weekLabel}</span>
          <button
            onClick={() => setWeekOffset(w => w + 1)}
            className="border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 rounded-xl px-4 py-2.5 text-sm"
          >Siguiente →</button>
        </div>
        <div className="flex items-center gap-3">
          <span className="text-sm font-semibold text-slate-700 dark:text-slate-300">
            Total semana: <span className="text-blue-600 dark:text-blue-400 text-lg">{weekTotal}h</span>
          </span>
          <button
            onClick={() => setSaved(true)}
            className="bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium transition-colors"
          >
            {saved ? '✓ Guardado' : 'Guardar semana'}
          </button>
        </div>
      </div>

      {hasOvertime && (
        <div className="flex items-center gap-2 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700 rounded-xl px-4 py-3">
          <span className="text-amber-600 dark:text-amber-400 text-sm font-medium">
            ⚠ Hay días con más de 9 horas registradas. Revisa la carga de trabajo.
          </span>
        </div>
      )}

      {/* Grid */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-x-auto">
        <table className="w-full text-sm min-w-[700px]">
          <thead>
            <tr className="bg-slate-50 dark:bg-slate-800/60">
              <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left w-56">Tarea</th>
              {WEEK_LABELS.map(d => (
                <th key={d} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-2 py-3 text-center w-16">{d}</th>
              ))}
              <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-3 py-3 text-center">Total</th>
            </tr>
          </thead>
          <tbody>
            {filteredTasks.length === 0 ? (
              <tr><td colSpan={9} className="text-center py-8 text-slate-400 dark:text-slate-500">No hay tareas para el proyecto seleccionado</td></tr>
            ) : filteredTasks.map(task => {
              const proj = getProject(task.projectId);
              const row = userHours[task.id] || Array(7).fill(0);
              const rowTotal = row.reduce((a, b) => a + b, 0);
              return (
                <tr key={task.id} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                  <td className="px-4 py-2">
                    <p className="font-medium text-slate-800 dark:text-slate-200 text-xs">{task.code}</p>
                    <p className="text-slate-500 dark:text-slate-400 text-xs truncate max-w-[180px]">{task.name}</p>
                    <span
                      className="rounded-full px-2 py-0.5 text-xs font-medium mt-0.5 inline-block"
                      style={{ background: PROJECT_COLORS[task.projectId] + '22', color: PROJECT_COLORS[task.projectId] }}
                    >
                      {proj.code}
                    </span>
                  </td>
                  {row.map((h, di) => (
                    <td key={di} className="px-1 py-2 text-center">
                      <input
                        type="number" min="0" max="24" value={h || ''}
                        placeholder="0"
                        onChange={e => handleChange(task.id, di, e.target.value)}
                        className="w-12 text-center text-sm rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-slate-900 dark:text-white py-1 focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </td>
                  ))}
                  <td className="px-3 py-2 text-center font-semibold text-slate-700 dark:text-slate-300">{rowTotal}</td>
                </tr>
              );
            })}
          </tbody>
          <tfoot>
            <tr className="bg-slate-50 dark:bg-slate-800/60 border-t-2 border-slate-200 dark:border-slate-700">
              <td className="px-4 py-3 text-xs font-bold text-slate-500 dark:text-slate-400 uppercase">Total día</td>
              {dayTotals.map((t, i) => (
                <td key={i} className={`px-2 py-3 text-center text-sm font-bold ${t > 9 ? 'text-amber-600 dark:text-amber-400' : 'text-slate-700 dark:text-slate-300'}`}>{t}</td>
              ))}
              <td className="px-3 py-3 text-center text-sm font-bold text-blue-600 dark:text-blue-400">{weekTotal}</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  );
}

// ── Tab 2: Mi Resumen ────────────────────────────────────────────────────────

function MiResumen({ selectedProjectId }) {
  const byProject = [
    { name: 'AR-ProjectManagement', value: 0,  projectId:'p4', fill:'#3b82f6' },
    { name: 'Álbum Horizontes',  value: 0,  projectId:'p4', fill:'#10b981' },
    { name: 'AR-ProjectManagement',   value: 0,  projectId:'p4', fill:'#ef4444' },
    { name: 'AR-ProjectMgmt',    value: 39, projectId:'p4', fill:'#8b5cf6' },
  ];
  // Current user (u1) works only on p4 this week
  byProject[3].value = 39;

  const filtered = byProject.filter(b => !selectedProjectId || b.projectId === selectedProjectId);
  const weekHours = filtered.reduce((s, b) => s + b.value, 0);
  const billable = Math.round(weekHours * 0.85);
  const nonBillable = weekHours - billable;

  const hasOvertime = WEEKLY_HISTORY.some(w => w.hours > 40);

  return (
    <div className="space-y-6">
      {hasOvertime && (
        <div className="flex items-center gap-2 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-700 rounded-xl px-4 py-3">
          <span className="text-amber-600 dark:text-amber-400 text-sm font-medium">
            ⚠ Tienes semanas con horas extra. Considera redistribuir carga.
          </span>
        </div>
      )}

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KPICard label="Horas esta semana"    value={`${weekHours}h`}     sub="Semana actual"          icon="⏱" accent="blue"   />
        <KPICard label="Horas este mes"       value="158h"                sub="Junio 2026"             icon="📅" accent="green"  />
        <KPICard label="Horas facturables"    value={`${billable}h`}      sub={`No-fact.: ${nonBillable}h`} icon="💰" accent="purple" />
        <KPICard label="Proyectos activos"    value={selectedProjectId ? '1' : '1'} sub="En curso"    icon="📁" accent="amber"  />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Donut by project */}
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
          <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-300 mb-4">Horas por proyecto (semana)</h3>
          <ResponsiveContainer width="100%" height={240}>
            <PieChart>
              <Pie data={filtered.filter(b => b.value > 0)} cx="50%" cy="50%" innerRadius={60} outerRadius={90}
                dataKey="value" nameKey="name" paddingAngle={3}>
                {filtered.filter(b => b.value > 0).map((entry, i) => (
                  <Cell key={i} fill={entry.fill} />
                ))}
              </Pie>
              <Tooltip formatter={(v) => [`${v}h`, 'Horas']} />
              <Legend />
            </PieChart>
          </ResponsiveContainer>
        </div>

        {/* Line chart last 8 weeks */}
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
          <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-300 mb-4">Horas por semana (últimas 8)</h3>
          <ResponsiveContainer width="100%" height={240}>
            <LineChart data={WEEKLY_HISTORY}>
              <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
              <XAxis dataKey="week" tick={{ fontSize: 11 }} />
              <YAxis domain={[30, 50]} tick={{ fontSize: 11 }} />
              <Tooltip formatter={(v) => [`${v}h`, 'Horas']} />
              <Line type="monotone" dataKey="hours" stroke="#3b82f6" strokeWidth={2} dot={{ r: 4 }} name="Horas" />
            </LineChart>
          </ResponsiveContainer>
        </div>
      </div>
    </div>
  );
}

// ── Tab 3: Reporte de Equipo ─────────────────────────────────────────────────

function ReporteEquipo({ selectedProjectId }) {
  const filtered = TEAM_REPORT.filter(r => !selectedProjectId || r.projectId === selectedProjectId);

  const totalHours = filtered.reduce((s, r) => s + r.thisWeek, 0);
  const member = (id) => TEAM_MEMBERS.find(m => m.id === id) || {};
  const totalCost = filtered.reduce((s, r) => {
    const m = member(r.userId);
    return s + r.thisWeek * (m.rate || 55);
  }, 0);
  const billableRevenue = filtered.reduce((s, r) => {
    const m = member(r.userId);
    return s + r.thisWeek * (m.rate || 55) * (r.billablePct / 100);
  }, 0);

  return (
    <div className="space-y-6">
      {/* Summary KPIs */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <KPICard label="Horas equipo (semana)" value={`${totalHours}h`}       sub={`${filtered.length} miembros`}        icon="👥" accent="blue"   />
        <KPICard label="Costo total (semana)"  value={`$${totalCost.toLocaleString()}`} sub="USD (horas × tarifa)"      icon="💵" accent="amber"  />
        <KPICard label="Revenue facturable"    value={`$${Math.round(billableRevenue).toLocaleString()}`} sub="Horas facturables" icon="📈" accent="green" />
      </div>

      {/* Table */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-x-auto">
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 dark:border-slate-800">
          <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-300">Detalle por miembro</h3>
          <button className="border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 rounded-xl px-4 py-2.5 text-sm">
            Exportar →
          </button>
        </div>
        <table className="w-full text-sm min-w-[700px]">
          <thead>
            <tr className="bg-slate-50 dark:bg-slate-800/60">
              {['Persona', 'Proyecto', 'Esta semana', 'Este mes', 'YTD', 'Facturable %', 'Estado'].map(h => (
                <th key={h} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => {
              const m = member(r.userId);
              const proj = getProject(r.projectId);
              const stColor = statusColor(r.thisWeek, r.planned);
              const ratio = r.thisWeek / r.planned;
              const statusLabel = ratio <= 1.10 ? 'Normal' : ratio <= 1.20 ? 'Alerta' : 'Excedido';
              const statusBadge = ratio <= 1.10
                ? 'bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400'
                : ratio <= 1.20
                ? 'bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400'
                : 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400';
              return (
                <tr key={r.userId} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold text-white" style={{ background: m.color }}>{m.avatar}</div>
                      <div>
                        <p className="font-medium text-slate-800 dark:text-slate-200">{m.name}</p>
                        <p className="text-xs text-slate-400">{m.role} · ${m.rate}/h</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className="rounded-full px-2.5 py-0.5 text-xs font-medium"
                      style={{ background: PROJECT_COLORS[r.projectId] + '22', color: PROJECT_COLORS[r.projectId] }}>
                      {proj.code}
                    </span>
                  </td>
                  <td className={`px-4 py-3 font-semibold ${stColor}`}>{r.thisWeek}h</td>
                  <td className="px-4 py-3 text-slate-700 dark:text-slate-300">{r.thisMonth}h</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400">{r.ytd}h</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-20 h-1.5 rounded-full bg-slate-200 dark:bg-slate-700">
                        <div className="h-1.5 rounded-full bg-blue-500" style={{ width: `${r.billablePct}%` }} />
                      </div>
                      <span className="text-xs text-slate-600 dark:text-slate-400">{r.billablePct}%</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${statusBadge}`}>{statusLabel}</span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Tab 4: Por Proyecto ──────────────────────────────────────────────────────

function PorProyecto({ selectedProjectId }) {
  const [localProject, setLocalProject] = useState(selectedProjectId || 'p4');

  const projId = selectedProjectId || localProject;
  const tasks = PROJECT_TASK_DATA[projId] || [];
  const proj = getProject(projId);

  const chartData = tasks.map(t => ({
    name: t.task,
    Planificado: t.estimated,
    Real: t.actual,
  }));

  const totalEstimated = tasks.reduce((s, t) => s + t.estimated, 0);
  const totalActual = tasks.reduce((s, t) => s + t.actual, 0);

  return (
    <div className="space-y-6">
      {/* Project selector (only when no global filter) */}
      {!selectedProjectId && (
        <div className="flex items-center gap-3">
          <label className="text-sm font-medium text-slate-700 dark:text-slate-300">Proyecto:</label>
          <select
            value={localProject}
            onChange={e => setLocalProject(e.target.value)}
            className="border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-700 dark:text-slate-300 rounded-xl px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            {MOCK_PROJECTS.map(p => (
              <option key={p.id} value={p.id}>{p.code} — {p.name}</option>
            ))}
          </select>
        </div>
      )}

      {/* EVM note */}
      <div className="flex items-center gap-2 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-xl px-4 py-3">
        <span className="text-blue-700 dark:text-blue-300 text-sm">
          ℹ Estas horas alimentan automáticamente el cálculo de AC (Actual Cost) en el módulo EVM.
        </span>
      </div>

      {/* Bar chart */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
        <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-300 mb-4">
          Horas planificadas vs reales — {proj.name}
        </h3>
        <ResponsiveContainer width="100%" height={280}>
          <BarChart data={chartData} margin={{ top: 0, right: 16, left: 0, bottom: 0 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
            <XAxis dataKey="name" tick={{ fontSize: 11 }} />
            <YAxis tick={{ fontSize: 11 }} />
            <Tooltip formatter={(v) => [`${v}h`]} />
            <Legend />
            <Bar dataKey="Planificado" fill="#3b82f6" radius={[4,4,0,0]} />
            <Bar dataKey="Real" fill="#ef4444" radius={[4,4,0,0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>

      {/* Task table */}
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-x-auto">
        <table className="w-full text-sm min-w-[600px]">
          <thead>
            <tr className="bg-slate-50 dark:bg-slate-800/60">
              {['Tarea', 'Responsable', 'Estimado', 'Real', 'Restante', '% Completo', 'Varianza'].map(h => (
                <th key={h} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {tasks.map(t => {
              const remaining = Math.max(0, t.estimated - t.actual);
              const variance = t.actual - t.estimated;
              const varColor = varianceColor(t.estimated, t.actual);
              return (
                <tr key={t.task} className="border-t border-slate-100 dark:border-slate-800 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                  <td className="px-4 py-3">
                    <p className="font-medium text-slate-800 dark:text-slate-200 text-xs">{t.task}</p>
                    <p className="text-slate-500 dark:text-slate-400 text-xs">{t.name}</p>
                  </td>
                  <td className="px-4 py-3 text-slate-700 dark:text-slate-300">{t.assignee}</td>
                  <td className="px-4 py-3 text-slate-700 dark:text-slate-300">{t.estimated}h</td>
                  <td className="px-4 py-3 text-slate-700 dark:text-slate-300">{t.actual}h</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400">{remaining}h</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-16 h-1.5 rounded-full bg-slate-200 dark:bg-slate-700">
                        <div className="h-1.5 rounded-full bg-blue-500" style={{ width: `${Math.min(100, t.pct)}%` }} />
                      </div>
                      <span className="text-xs text-slate-600 dark:text-slate-400">{t.pct}%</span>
                    </div>
                  </td>
                  <td className={`px-4 py-3 font-semibold ${varColor}`}>
                    {variance > 0 ? `+${variance}h` : variance === 0 ? '—' : `${variance}h`}
                  </td>
                </tr>
              );
            })}
          </tbody>
          <tfoot>
            <tr className="bg-slate-50 dark:bg-slate-800/60 border-t-2 border-slate-200 dark:border-slate-700">
              <td colSpan={2} className="px-4 py-3 text-xs font-bold text-slate-500 dark:text-slate-400 uppercase">Total</td>
              <td className="px-4 py-3 font-bold text-slate-700 dark:text-slate-300">{totalEstimated}h</td>
              <td className={`px-4 py-3 font-bold ${varianceColor(totalEstimated, totalActual)}`}>{totalActual}h</td>
              <td className="px-4 py-3 font-bold text-slate-500 dark:text-slate-400">{Math.max(0, totalEstimated - totalActual)}h</td>
              <td colSpan={2} />
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  );
}

// ── Main Page ────────────────────────────────────────────────────────────────

const TABS = [
  { id: 'registro',  label: 'Registro de Horas' },
  { id: 'resumen',   label: 'Mi Resumen' },
  { id: 'equipo',    label: 'Reporte de Equipo' },
  { id: 'proyecto',  label: 'Por Proyecto' },
];

export default function TimeTrackingPage() {
  const { selectedProjectId } = useProject();
  const [activeTab, setActiveTab] = useState('registro');

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-4 md:p-6 lg:p-8">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* Header */}
        <div>
          <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Control de Horas</h1>
          <p className="text-slate-500 dark:text-slate-400 mt-1 text-sm">
            Registra y analiza las horas trabajadas. Los datos alimentan EVM automáticamente.
          </p>
        </div>

        {/* Tabs */}
        <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
          <div className="flex border-b border-slate-200 dark:border-slate-700 mb-6 -mt-1 gap-1 overflow-x-auto">
            {TABS.map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`px-4 py-2.5 text-sm font-medium whitespace-nowrap transition-colors ${
                  activeTab === tab.id
                    ? 'border-b-2 border-blue-600 text-blue-600 dark:text-blue-400'
                    : 'border-b-2 border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300'
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {activeTab === 'registro' && <RegistroHoras selectedProjectId={selectedProjectId} />}
          {activeTab === 'resumen'  && <MiResumen     selectedProjectId={selectedProjectId} />}
          {activeTab === 'equipo'   && <ReporteEquipo selectedProjectId={selectedProjectId} />}
          {activeTab === 'proyecto' && <PorProyecto   selectedProjectId={selectedProjectId} />}
        </div>
      </div>
    </div>
  );
}
