import React, { useState, useMemo } from 'react';
import { useProject } from '../../context/ProjectContext';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, Legend,
} from 'recharts';

// ── Mock data ──────────────────────────────────────────────────────────────────
const MOCK_INVOICES = [
  { id:'FAC-2026-001', client:'Constructora Andina S.A.', project:'AR-ProjectManagement', projectCode:'PRY-001', projectId:'p4',
    concept:'Anticipo 30% — Contrato CT-2025-047', amount:255000000, tax:48450000, total:303450000,
    currency:'COP', issueDate:'2026-03-15', dueDate:'2026-03-30', status:'PAGADA',
    paidDate:'2026-03-28', paidAmount:303450000, paymentRef:'TRF-20260328' },
  { id:'FAC-2026-002', client:'Constructora Andina S.A.', project:'AR-ProjectManagement', projectCode:'PRY-001', projectId:'p4',
    concept:'Acta parcial #1 — Avance 25% estructura', amount:170000000, tax:32300000, total:202300000,
    currency:'COP', issueDate:'2026-05-10', dueDate:'2026-06-10', status:'PAGADA',
    paidDate:'2026-06-08', paidAmount:202300000, paymentRef:'TRF-20260608' },
  { id:'FAC-2026-003', client:'Constructora Andina S.A.', project:'AR-ProjectManagement', projectCode:'PRY-001', projectId:'p4',
    concept:'Acta parcial #2 — Avance 15% instalaciones', amount:127500000, tax:24225000, total:151725000,
    currency:'COP', issueDate:'2026-06-20', dueDate:'2026-07-20', status:'PENDIENTE',
    paidDate:null, paidAmount:0, paymentRef:null },
  { id:'FAC-2026-004', client:'TechCorp Colombia', project:'AR-ProjectManagement', projectCode:'PRY-002', projectId:'p4',
    concept:'Fase 1 — Análisis y diseño', amount:45000000, tax:8550000, total:53550000,
    currency:'COP', issueDate:'2026-04-01', dueDate:'2026-04-30', status:'PAGADA',
    paidDate:'2026-04-25', paidAmount:53550000, paymentRef:'TRF-20260425' },
  { id:'FAC-2026-005', client:'TechCorp Colombia', project:'AR-ProjectManagement', projectCode:'PRY-002', projectId:'p4',
    concept:'Fase 2 — Desarrollo módulos core', amount:85000000, tax:16150000, total:101150000,
    currency:'COP', issueDate:'2026-06-01', dueDate:'2026-07-01', status:'VENCIDA',
    paidDate:null, paidAmount:0, paymentRef:null },
  { id:'FAC-2026-006', client:'Energía del Pacífico', project:'Subestación Eléctrica', projectCode:'PRY-003', projectId:'p4',
    concept:'Anticipo 40% — Ingeniería básica', amount:120000000, tax:22800000, total:142800000,
    currency:'COP', issueDate:'2026-05-20', dueDate:'2026-06-20', status:'PAGADA',
    paidDate:'2026-06-15', paidAmount:142800000, paymentRef:'TRF-20260615' },
  { id:'FAC-2026-007', client:'Logística Nacional S.A.', project:'Bodega Industrial Norte', projectCode:'PRY-004', projectId:'p4',
    concept:'Anticipo 30% — Diseño y permisos', amount:63000000, tax:11970000, total:74970000,
    currency:'COP', issueDate:'2026-06-10', dueDate:'2026-07-10', status:'PENDIENTE',
    paidDate:null, paidAmount:0, paymentRef:null },
  { id:'FAC-2026-008', client:'TechCorp Colombia', project:'AR-ProjectManagement', projectCode:'PRY-002', projectId:'p4',
    concept:'Fase 2 — Ajuste por alcance adicional', amount:18000000, tax:3420000, total:21420000,
    currency:'COP', issueDate:'2026-06-25', dueDate:'2026-07-25', status:'BORRADOR',
    paidDate:null, paidAmount:0, paymentRef:null },
];

const MOCK_MILESTONES = [
  { project:'AR-ProjectManagement', hito:'Anticipo 30%',            pct:30, amount:255000000, invoiced:true,  invoiceRef:'FAC-2026-001', status:'COBRADO' },
  { project:'AR-ProjectManagement', hito:'Acta parcial #1 (25%)',   pct:25, amount:212500000, invoiced:true,  invoiceRef:'FAC-2026-002', status:'COBRADO' },
  { project:'AR-ProjectManagement', hito:'Acta parcial #2 (15%)',   pct:15, amount:127500000, invoiced:true,  invoiceRef:'FAC-2026-003', status:'PENDIENTE' },
  { project:'AR-ProjectManagement', hito:'Acta parcial #3 (20%)',   pct:20, amount:170000000, invoiced:false, invoiceRef:null,           status:'POR_FACTURAR' },
  { project:'AR-ProjectManagement', hito:'Liquidación final (10%)', pct:10, amount:85000000,  invoiced:false, invoiceRef:null,           status:'POR_FACTURAR' },
  { project:'AR-ProjectManagement',   hito:'Fase 1 (20%)',            pct:20, amount:45000000,  invoiced:true,  invoiceRef:'FAC-2026-004', status:'COBRADO' },
  { project:'AR-ProjectManagement',   hito:'Fase 2 (38%)',            pct:38, amount:85000000,  invoiced:true,  invoiceRef:'FAC-2026-005', status:'VENCIDO' },
  { project:'AR-ProjectManagement',   hito:'Fase 3 (42%)',            pct:42, amount:94500000,  invoiced:false, invoiceRef:null,           status:'POR_FACTURAR' },
];

const MOCK_RETENTIONS = [
  { project:'AR-ProjectManagement', contract:'CT-2025-047', contractValue:850000000, retentionPct:10, retained:85000000,  releaseDate:'2027-03-01', status:'RETENIDO' },
  { project:'AR-ProjectManagement',   contract:'CT-2026-012', contractValue:225000000, retentionPct:5,  retained:11250000, releaseDate:'2026-12-01', status:'RETENIDO' },
  { project:'Subestación',       contract:'CT-2026-008', contractValue:300000000, retentionPct:10, retained:30000000, releaseDate:'2027-06-01', status:'RETENIDO' },
];

// ── Helpers ────────────────────────────────────────────────────────────────────
const fmt = (n) =>
  new Intl.NumberFormat('es-CO', { style: 'currency', currency: 'COP', maximumFractionDigits: 0 }).format(n);

const fmtDate = (d) => {
  if (!d) return '—';
  const [y, m, day] = d.split('-');
  return `${day}/${m}/${y}`;
};

const TABS = ['Facturas emitidas', 'Hitos de cobro', 'Estado de cuenta', 'Retenciones'];

// ── Status badge ───────────────────────────────────────────────────────────────
const STATUS_INVOICE = {
  PAGADA:    { cls: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20', label: 'Pagada' },
  PENDIENTE: { cls: 'bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400 border-amber-200 dark:border-amber-500/20', label: 'Pendiente' },
  VENCIDA:   { cls: 'bg-red-50 text-red-700 dark:bg-red-500/10 dark:text-red-400 border-red-200 dark:border-red-500/20', label: 'Vencida', pulse: true },
  BORRADOR:  { cls: 'bg-slate-100 text-slate-600 dark:bg-slate-700/50 dark:text-slate-400 border-slate-200 dark:border-slate-600', label: 'Borrador' },
};

const STATUS_MILESTONE = {
  COBRADO:      { cls: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20', label: 'Cobrado' },
  PENDIENTE:    { cls: 'bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400 border-amber-200 dark:border-amber-500/20', label: 'Pendiente' },
  VENCIDO:      { cls: 'bg-red-50 text-red-700 dark:bg-red-500/10 dark:text-red-400 border-red-200 dark:border-red-500/20', label: 'Vencido', pulse: true },
  POR_FACTURAR: { cls: 'bg-blue-50 text-blue-700 dark:bg-blue-500/10 dark:text-blue-400 border-blue-200 dark:border-blue-500/20', label: 'Por facturar' },
};

function Badge({ statusMap, status }) {
  const s = statusMap[status] || { cls: 'bg-slate-100 text-slate-600', label: status };
  return (
    <span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium border ${s.cls}`}>
      {s.pulse && <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />}
      {s.label}
    </span>
  );
}

// ── KPI Card ───────────────────────────────────────────────────────────────────
function KpiCard({ label, value, color = 'text-slate-800 dark:text-slate-100', sub }) {
  return (
    <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-surface-800 px-5 py-4 flex flex-col gap-1">
      <span className="text-xs text-slate-500 dark:text-slate-400 font-medium uppercase tracking-wide">{label}</span>
      <span className={`text-xl font-bold ${color}`}>{value}</span>
      {sub && <span className="text-xs text-slate-400">{sub}</span>}
    </div>
  );
}

// ── Modal base ─────────────────────────────────────────────────────────────────
function Modal({ title, onClose, children, wide = false }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
      <div className={`bg-white dark:bg-surface-800 rounded-2xl shadow-2xl border border-slate-200 dark:border-surface-700 w-full ${wide ? 'max-w-3xl' : 'max-w-xl'} max-h-[90vh] overflow-y-auto`}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 dark:border-surface-700">
          <h2 className="text-base font-semibold text-slate-800 dark:text-slate-100">{title}</h2>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 transition-colors text-xl leading-none">&times;</button>
        </div>
        <div className="px-6 py-5">{children}</div>
      </div>
    </div>
  );
}

// ── Tab 0: Facturas emitidas ───────────────────────────────────────────────────
function InvoicesTab() {
  const { selectedProjectId } = useProject();
  const [invoices, setInvoices] = useState(MOCK_INVOICES);
  const [viewInv, setViewInv]   = useState(null);
  const [showPay, setShowPay]   = useState(false);
  const [showNew, setShowNew]   = useState(false);

  // Pay form state
  const [payForm, setPayForm] = useState({ monto: '', fecha: '', ref: '' });

  // New invoice form state
  const [newForm, setNewForm] = useState({
    client: '', project: '', concept: '',
    amount: '', ivaPct: '19', issueDate: '', dueDate: '',
  });

  const clients = [...new Set(MOCK_INVOICES.map(i => i.client))];
  const projects = [...new Set(MOCK_INVOICES.map(i => i.project))];

  const filteredInvoices = useMemo(() =>
    invoices.filter(i => !selectedProjectId || i.projectId === selectedProjectId),
    [invoices, selectedProjectId]
  );

  const kpis = useMemo(() => {
    const facturado = filteredInvoices.reduce((a, i) => a + i.total, 0);
    const cobrado   = filteredInvoices.filter(i => i.status === 'PAGADA').reduce((a, i) => a + i.paidAmount, 0);
    const porCobrar = filteredInvoices.filter(i => i.status === 'PENDIENTE').reduce((a, i) => a + i.total, 0);
    const vencido   = filteredInvoices.filter(i => i.status === 'VENCIDA').reduce((a, i) => a + i.total, 0);
    return { facturado, cobrado, porCobrar, vencido };
  }, [filteredInvoices]);

  const handleRegisterPay = () => {
    setInvoices(prev => prev.map(inv =>
      inv.id === viewInv.id
        ? { ...inv, status: 'PAGADA', paidDate: payForm.fecha, paidAmount: parseFloat(payForm.monto) || inv.total, paymentRef: payForm.ref }
        : inv
    ));
    setShowPay(false);
    setViewInv(null);
    setPayForm({ monto: '', fecha: '', ref: '' });
  };

  const handleNewInvoice = () => {
    const sub   = parseFloat(newForm.amount) || 0;
    const tax   = sub * (parseFloat(newForm.ivaPct) / 100);
    const total = sub + tax;
    const id    = `FAC-2026-${String(invoices.length + 1).padStart(3, '0')}`;
    setInvoices(prev => [...prev, {
      id, client: newForm.client, project: newForm.project, projectCode: 'PRY-NEW',
      concept: newForm.concept, amount: sub, tax, total,
      currency: 'COP', issueDate: newForm.issueDate, dueDate: newForm.dueDate,
      status: 'BORRADOR', paidDate: null, paidAmount: 0, paymentRef: null,
    }]);
    setShowNew(false);
    setNewForm({ client: '', project: '', concept: '', amount: '', ivaPct: '19', issueDate: '', dueDate: '' });
  };

  const currentInv = viewInv ? invoices.find(i => i.id === viewInv.id) : null;

  return (
    <div className="space-y-5">
      {/* KPIs */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KpiCard label="Total facturado" value={fmt(kpis.facturado)} color="text-blue-600 dark:text-blue-400" />
        <KpiCard label="Total cobrado"   value={fmt(kpis.cobrado)}   color="text-emerald-600 dark:text-emerald-400" />
        <KpiCard label="Por cobrar"      value={fmt(kpis.porCobrar)} color="text-amber-600 dark:text-amber-400" />
        <KpiCard label="Vencido"         value={fmt(kpis.vencido)}   color="text-red-600 dark:text-red-400" />
      </div>

      {/* Header */}
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-200">Facturas emitidas ({invoices.length})</h3>
        <button
          onClick={() => setShowNew(true)}
          className="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors shadow-sm"
        >
          <span className="text-lg leading-none">+</span> Nueva factura
        </button>
      </div>

      {/* Table */}
      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 overflow-hidden bg-white dark:bg-surface-800">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 dark:bg-surface-900/60 text-left">
                {['N° Factura','Cliente','Proyecto','Concepto','Subtotal','IVA','Total','Emisión','Vencimiento','Estado','Acciones'].map(h => (
                  <th key={h} className="px-4 py-3 text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100 dark:divide-surface-700">
              {filteredInvoices.map(inv => (
                <tr
                  key={inv.id}
                  className={`transition-colors hover:bg-slate-50 dark:hover:bg-surface-700/40 ${inv.status === 'VENCIDA' ? 'bg-red-50/60 dark:bg-red-500/5' : ''}`}
                >
                  <td className="px-4 py-3 font-mono text-xs text-blue-600 dark:text-blue-400 font-semibold whitespace-nowrap">{inv.id}</td>
                  <td className="px-4 py-3 text-slate-700 dark:text-slate-300 whitespace-nowrap">{inv.client}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-400 whitespace-nowrap">{inv.project}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-400 max-w-[200px] truncate" title={inv.concept}>{inv.concept}</td>
                  <td className="px-4 py-3 text-slate-700 dark:text-slate-300 whitespace-nowrap text-right">{fmt(inv.amount)}</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap text-right">{fmt(inv.tax)}</td>
                  <td className="px-4 py-3 font-semibold text-slate-800 dark:text-slate-100 whitespace-nowrap text-right">{fmt(inv.total)}</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{fmtDate(inv.issueDate)}</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{fmtDate(inv.dueDate)}</td>
                  <td className="px-4 py-3 whitespace-nowrap"><Badge statusMap={STATUS_INVOICE} status={inv.status} /></td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <button
                      onClick={() => setViewInv(inv)}
                      className="px-3 py-1 rounded-lg text-xs font-medium bg-slate-100 dark:bg-surface-700 text-slate-700 dark:text-slate-300 hover:bg-blue-50 dark:hover:bg-blue-500/10 hover:text-blue-700 dark:hover:text-blue-400 transition-colors"
                    >
                      Ver
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modal: Ver factura */}
      {currentInv && (
        <Modal title={`Detalle — ${currentInv.id}`} onClose={() => { setViewInv(null); setShowPay(false); }} wide>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <Field label="Cliente"    value={currentInv.client} />
              <Field label="Proyecto"   value={`${currentInv.project} (${currentInv.projectCode})`} />
              <Field label="Concepto"   value={currentInv.concept} span />
              <Field label="Subtotal"   value={fmt(currentInv.amount)} />
              <Field label="IVA"        value={fmt(currentInv.tax)} />
              <Field label="Total"      value={fmt(currentInv.total)} highlight />
              <Field label="Fecha emisión"    value={fmtDate(currentInv.issueDate)} />
              <Field label="Fecha vencimiento" value={fmtDate(currentInv.dueDate)} />
              <Field label="Estado"     value={<Badge statusMap={STATUS_INVOICE} status={currentInv.status} />} />
              {currentInv.paidDate && <Field label="Fecha pago" value={fmtDate(currentInv.paidDate)} />}
              {currentInv.paidAmount > 0 && <Field label="Monto pagado" value={fmt(currentInv.paidAmount)} />}
              {currentInv.paymentRef && <Field label="Referencia" value={currentInv.paymentRef} />}
            </div>

            {(currentInv.status === 'PENDIENTE' || currentInv.status === 'VENCIDA') && !showPay && (
              <button
                onClick={() => { setShowPay(true); setPayForm({ monto: currentInv.total, fecha: '', ref: '' }); }}
                className="mt-2 w-full py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium transition-colors"
              >
                Registrar pago
              </button>
            )}

            {showPay && (
              <div className="border border-slate-200 dark:border-surface-700 rounded-xl p-4 space-y-3 bg-slate-50 dark:bg-surface-900/40 mt-2">
                <p className="text-sm font-semibold text-slate-700 dark:text-slate-200 mb-1">Registrar pago recibido</p>
                <FormField label="Monto recibido (COP)" type="number" value={payForm.monto}
                  onChange={v => setPayForm(p => ({ ...p, monto: v }))} />
                <FormField label="Fecha de pago" type="date" value={payForm.fecha}
                  onChange={v => setPayForm(p => ({ ...p, fecha: v }))} />
                <FormField label="Referencia bancaria" value={payForm.ref}
                  onChange={v => setPayForm(p => ({ ...p, ref: v }))} />
                <div className="flex gap-2 pt-1">
                  <button onClick={handleRegisterPay}
                    className="flex-1 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium transition-colors">
                    Confirmar pago
                  </button>
                  <button onClick={() => setShowPay(false)}
                    className="flex-1 py-2 rounded-xl border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-slate-300 text-sm hover:bg-slate-100 dark:hover:bg-surface-700 transition-colors">
                    Cancelar
                  </button>
                </div>
              </div>
            )}
          </div>
        </Modal>
      )}

      {/* Modal: Nueva factura */}
      {showNew && (
        <Modal title="Nueva factura" onClose={() => setShowNew(false)}>
          <div className="space-y-3">
            <div>
              <label className="text-xs font-medium text-slate-600 dark:text-slate-400 mb-1 block">Cliente</label>
              <select value={newForm.client} onChange={e => setNewForm(p => ({ ...p, client: e.target.value }))}
                className="w-full rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-slate-100 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/40">
                <option value="">Seleccionar cliente…</option>
                {clients.map(c => <option key={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className="text-xs font-medium text-slate-600 dark:text-slate-400 mb-1 block">Proyecto</label>
              <select value={newForm.project} onChange={e => setNewForm(p => ({ ...p, project: e.target.value }))}
                className="w-full rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-slate-100 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/40">
                <option value="">Seleccionar proyecto…</option>
                {projects.map(p => <option key={p}>{p}</option>)}
              </select>
            </div>
            <FormField label="Concepto" value={newForm.concept} onChange={v => setNewForm(p => ({ ...p, concept: v }))} />
            <FormField label="Subtotal (COP)" type="number" value={newForm.amount} onChange={v => setNewForm(p => ({ ...p, amount: v }))} />
            <div>
              <label className="text-xs font-medium text-slate-600 dark:text-slate-400 mb-1 block">% IVA</label>
              <div className="flex items-center gap-3">
                <input type="number" value={newForm.ivaPct} onChange={e => setNewForm(p => ({ ...p, ivaPct: e.target.value }))}
                  className="w-24 rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-slate-100 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/40" />
                {newForm.amount && (
                  <span className="text-sm text-slate-500 dark:text-slate-400">
                    IVA: {fmt(parseFloat(newForm.amount) * parseFloat(newForm.ivaPct) / 100)} →
                    Total: {fmt(parseFloat(newForm.amount) * (1 + parseFloat(newForm.ivaPct) / 100))}
                  </span>
                )}
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <FormField label="Fecha emisión"    type="date" value={newForm.issueDate} onChange={v => setNewForm(p => ({ ...p, issueDate: v }))} />
              <FormField label="Fecha vencimiento" type="date" value={newForm.dueDate}  onChange={v => setNewForm(p => ({ ...p, dueDate: v }))} />
            </div>
            <div className="flex gap-2 pt-2">
              <button onClick={handleNewInvoice}
                className="flex-1 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors">
                Crear factura
              </button>
              <button onClick={() => setShowNew(false)}
                className="flex-1 py-2 rounded-xl border border-slate-200 dark:border-surface-600 text-slate-600 dark:text-slate-300 text-sm hover:bg-slate-100 dark:hover:bg-surface-700 transition-colors">
                Cancelar
              </button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}

// ── Tab 1: Hitos de cobro ──────────────────────────────────────────────────────
function MilestonesTab() {
  const [milestones, setMilestones] = useState(MOCK_MILESTONES);

  const projects = [...new Set(milestones.map(m => m.project))];

  const handleBill = (idx) => {
    setMilestones(prev => prev.map((m, i) =>
      i === idx ? { ...m, invoiced: true, status: 'PENDIENTE', invoiceRef: `FAC-2026-NEW` } : m
    ));
  };

  return (
    <div className="space-y-6">
      {projects.map(proj => {
        const items = milestones.filter(m => m.project === proj);
        const total = items.reduce((a, m) => a + m.amount, 0);
        const cobrado = items.filter(m => m.status === 'COBRADO').reduce((a, m) => a + m.amount, 0);
        return (
          <div key={proj} className="rounded-2xl border border-slate-200 dark:border-surface-700 overflow-hidden bg-white dark:bg-surface-800">
            <div className="px-5 py-3 bg-slate-50 dark:bg-surface-900/60 border-b border-slate-100 dark:border-surface-700 flex items-center justify-between">
              <div>
                <h3 className="text-sm font-semibold text-slate-800 dark:text-slate-100">{proj}</h3>
                <p className="text-xs text-slate-400 mt-0.5">
                  Cobrado: {fmt(cobrado)} / {fmt(total)} ({Math.round(cobrado / total * 100)}%)
                </p>
              </div>
              <div className="w-40 bg-slate-200 dark:bg-surface-700 rounded-full h-2">
                <div className="h-2 rounded-full bg-emerald-500 transition-all" style={{ width: `${cobrado / total * 100}%` }} />
              </div>
            </div>
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left">
                  {['Hito','%','Monto','N° Factura','Estado',''].map(h => (
                    <th key={h} className="px-4 py-2.5 text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 dark:divide-surface-700">
                {items.map((m, idx) => {
                  const globalIdx = milestones.indexOf(m);
                  return (
                    <tr key={idx} className="hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors">
                      <td className="px-4 py-3 text-slate-700 dark:text-slate-300 font-medium">{m.hito}</td>
                      <td className="px-4 py-3 text-slate-500 dark:text-slate-400">{m.pct}%</td>
                      <td className="px-4 py-3 text-slate-700 dark:text-slate-200 font-semibold">{fmt(m.amount)}</td>
                      <td className="px-4 py-3 font-mono text-xs text-blue-600 dark:text-blue-400">{m.invoiceRef || '—'}</td>
                      <td className="px-4 py-3"><Badge statusMap={STATUS_MILESTONE} status={m.status} /></td>
                      <td className="px-4 py-3">
                        {m.status === 'POR_FACTURAR' && (
                          <button
                            onClick={() => handleBill(globalIdx)}
                            className="px-3 py-1 rounded-lg text-xs font-medium bg-blue-50 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-500/20 border border-blue-200 dark:border-blue-500/30 transition-colors"
                          >
                            Facturar
                          </button>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        );
      })}
    </div>
  );
}

// ── Tab 2: Estado de cuenta ────────────────────────────────────────────────────
function AccountStateTab() {
  const clients = [...new Set(MOCK_INVOICES.map(i => i.client))];
  const [selectedClient, setSelectedClient] = useState(clients[0]);

  const clientInvoices = useMemo(() =>
    MOCK_INVOICES.filter(i => i.client === selectedClient),
    [selectedClient]
  );

  const summary = useMemo(() => {
    const facturado = clientInvoices.reduce((a, i) => a + i.total, 0);
    const cobrado   = clientInvoices.filter(i => i.status === 'PAGADA').reduce((a, i) => a + i.paidAmount, 0);
    const saldo     = facturado - cobrado;
    const vencido   = clientInvoices.filter(i => i.status === 'VENCIDA').reduce((a, i) => a + i.total, 0);
    return { facturado, cobrado, saldo, vencido };
  }, [clientInvoices]);

  // Build monthly chart data
  const chartData = useMemo(() => {
    const months = {};
    clientInvoices.forEach(inv => {
      const m = inv.issueDate?.slice(0, 7);
      if (!m) return;
      if (!months[m]) months[m] = { mes: m.slice(5) + '/' + m.slice(2, 4), facturado: 0, cobrado: 0 };
      months[m].facturado += inv.total;
      if (inv.status === 'PAGADA') months[m].cobrado += inv.paidAmount;
    });
    return Object.values(months).sort((a, b) => a.mes.localeCompare(b.mes));
  }, [clientInvoices]);

  return (
    <div className="space-y-5">
      {/* Selector */}
      <div className="flex items-center gap-3">
        <label className="text-sm font-medium text-slate-600 dark:text-slate-400 whitespace-nowrap">Cliente:</label>
        <select
          value={selectedClient}
          onChange={e => setSelectedClient(e.target.value)}
          className="rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-slate-100 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/40"
        >
          {clients.map(c => <option key={c}>{c}</option>)}
        </select>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KpiCard label="Total facturado" value={fmt(summary.facturado)} color="text-blue-600 dark:text-blue-400" />
        <KpiCard label="Total cobrado"   value={fmt(summary.cobrado)}   color="text-emerald-600 dark:text-emerald-400" />
        <KpiCard label="Saldo pendiente" value={fmt(summary.saldo)}     color="text-amber-600 dark:text-amber-400" />
        <KpiCard label="Vencido"         value={fmt(summary.vencido)}   color="text-red-600 dark:text-red-400" />
      </div>

      {/* Chart */}
      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-surface-800 p-5">
        <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-200 mb-4">Flujo de facturación vs cobro por mes</h3>
        <ResponsiveContainer width="100%" height={220}>
          <BarChart data={chartData} barGap={4}>
            <CartesianGrid strokeDasharray="3 3" stroke="rgba(148,163,184,.15)" />
            <XAxis dataKey="mes" tick={{ fontSize: 11, fill: '#94a3b8' }} />
            <YAxis tickFormatter={v => `${(v/1e6).toFixed(0)}M`} tick={{ fontSize: 11, fill: '#94a3b8' }} width={48} />
            <Tooltip formatter={(v, n) => [fmt(v), n === 'facturado' ? 'Facturado' : 'Cobrado']} />
            <Legend formatter={v => v === 'facturado' ? 'Facturado' : 'Cobrado'} />
            <Bar dataKey="facturado" fill="#3b82f6" radius={[4,4,0,0]} />
            <Bar dataKey="cobrado"   fill="#10b981" radius={[4,4,0,0]} />
          </BarChart>
        </ResponsiveContainer>
      </div>

      {/* Invoice table */}
      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 overflow-hidden bg-white dark:bg-surface-800">
        <div className="px-5 py-3 border-b border-slate-100 dark:border-surface-700 bg-slate-50 dark:bg-surface-900/60">
          <h3 className="text-sm font-semibold text-slate-700 dark:text-slate-200">Facturas de {selectedClient}</h3>
        </div>
        <table className="w-full text-sm">
          <thead>
            <tr className="text-left">
              {['N° Factura','Proyecto','Concepto','Total','Vencimiento','Estado'].map(h => (
                <th key={h} className="px-4 py-2.5 text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100 dark:divide-surface-700">
            {clientInvoices.map(inv => (
              <tr key={inv.id} className={`hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors ${inv.status === 'VENCIDA' ? 'bg-red-50/60 dark:bg-red-500/5' : ''}`}>
                <td className="px-4 py-3 font-mono text-xs text-blue-600 dark:text-blue-400 font-semibold">{inv.id}</td>
                <td className="px-4 py-3 text-slate-600 dark:text-slate-400">{inv.project}</td>
                <td className="px-4 py-3 text-slate-600 dark:text-slate-400 max-w-[200px] truncate">{inv.concept}</td>
                <td className="px-4 py-3 font-semibold text-slate-800 dark:text-slate-100">{fmt(inv.total)}</td>
                <td className="px-4 py-3 text-slate-500 dark:text-slate-400">{fmtDate(inv.dueDate)}</td>
                <td className="px-4 py-3"><Badge statusMap={STATUS_INVOICE} status={inv.status} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Tab 3: Retenciones ─────────────────────────────────────────────────────────
function RetentionsTab() {
  const totalRetained = MOCK_RETENTIONS.reduce((a, r) => a + r.retained, 0);

  return (
    <div className="space-y-5">
      {/* KPI destacada */}
      <div className="rounded-2xl border-2 border-amber-300 dark:border-amber-500/40 bg-amber-50 dark:bg-amber-500/10 px-6 py-4 flex items-center justify-between">
        <div>
          <p className="text-xs font-semibold text-amber-700 dark:text-amber-400 uppercase tracking-wide">Total retenido</p>
          <p className="text-2xl font-bold text-amber-800 dark:text-amber-300 mt-0.5">{fmt(totalRetained)}</p>
          <p className="text-xs text-amber-600 dark:text-amber-500 mt-0.5">{MOCK_RETENTIONS.length} contratos con retención activa</p>
        </div>
        <div className="text-5xl opacity-30">🔒</div>
      </div>

      {/* Table */}
      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 overflow-hidden bg-white dark:bg-surface-800">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 dark:bg-surface-900/60 text-left">
                {['Proyecto','Contrato','Valor contrato','% Retención','Monto retenido','Liberación estimada','Estado'].map(h => (
                  <th key={h} className="px-4 py-3 text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wide whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100 dark:divide-surface-700">
              {MOCK_RETENTIONS.map((r, i) => (
                <tr key={i} className="hover:bg-slate-50 dark:hover:bg-surface-700/40 transition-colors">
                  <td className="px-4 py-3 font-medium text-slate-800 dark:text-slate-100">{r.project}</td>
                  <td className="px-4 py-3 font-mono text-xs text-slate-500 dark:text-slate-400">{r.contract}</td>
                  <td className="px-4 py-3 text-slate-700 dark:text-slate-300">{fmt(r.contractValue)}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-400">{r.retentionPct}%</td>
                  <td className="px-4 py-3 font-semibold text-amber-700 dark:text-amber-400">{fmt(r.retained)}</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400">{fmtDate(r.releaseDate)}</td>
                  <td className="px-4 py-3">
                    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${
                      r.status === 'RETENIDO'
                        ? 'bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400 border-amber-200 dark:border-amber-500/20'
                        : 'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400 border-emerald-200 dark:border-emerald-500/20'
                    }`}>
                      {r.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ── Small helpers ──────────────────────────────────────────────────────────────
function Field({ label, value, span = false, highlight = false }) {
  return (
    <div className={span ? 'col-span-2' : ''}>
      <p className="text-xs font-medium text-slate-400 dark:text-slate-500 mb-0.5">{label}</p>
      <p className={`text-sm ${highlight ? 'font-bold text-slate-900 dark:text-white' : 'text-slate-700 dark:text-slate-300'}`}>
        {value}
      </p>
    </div>
  );
}

function FormField({ label, value, onChange, type = 'text' }) {
  return (
    <div>
      <label className="text-xs font-medium text-slate-600 dark:text-slate-400 mb-1 block">{label}</label>
      <input
        type={type}
        value={value}
        onChange={e => onChange(e.target.value)}
        className="w-full rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-slate-100 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/40"
      />
    </div>
  );
}

// ── Main page ──────────────────────────────────────────────────────────────────
export default function BillingPage() {
  const [activeTab, setActiveTab] = useState(0);

  return (
    <div className="space-y-6 p-6">
      {/* Page header */}
      <div>
        <h1 className="text-2xl font-bold text-slate-900 dark:text-white">Facturación al cliente</h1>
        <p className="text-sm text-slate-500 dark:text-slate-400 mt-1">Gestión de facturas emitidas, hitos de cobro, estado de cuenta y retenciones</p>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 bg-slate-100 dark:bg-surface-900/60 rounded-2xl p-1 w-fit">
        {TABS.map((tab, i) => (
          <button
            key={tab}
            onClick={() => setActiveTab(i)}
            className={`px-4 py-2 rounded-xl text-sm font-medium transition-all ${
              activeTab === i
                ? 'bg-white dark:bg-surface-800 text-slate-800 dark:text-slate-100 shadow-sm'
                : 'text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200'
            }`}
          >
            {tab}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {activeTab === 0 && <InvoicesTab />}
      {activeTab === 1 && <MilestonesTab />}
      {activeTab === 2 && <AccountStateTab />}
      {activeTab === 3 && <RetentionsTab />}
    </div>
  );
}
