/* global React */
// Mis Compromisos Asignados — vista de la Institución Reportante
// HU.2.1 (cargar avance), HU.2.2 (historial), HU.2.3 (devolución para ajuste)

const { useState: useStateM, useMemo: useMemoM } = React;

function MisCompromisosScreen({ user, onOpenDetalle, onCargar }) {
  const I = window.Icons;
  const all = window.MIS_COMPROMISOS;
  const [filter, setFilter] = useStateM('todos');
  const [view, setView] = useStateM('cards'); // cards | tabla

  // Conteos por estado de ciclo
  const counts = useMemoM(() => {
    const c = { todos: all.length, pending: 0, draft: 0, in_review: 0, returned: 0, approved: 0, overdue: 0 };
    all.forEach(x => { c[x.estadoCiclo] = (c[x.estadoCiclo] || 0) + 1; });
    return c;
  }, [all]);

  const filtered = useMemoM(() => {
    if (filter === 'todos') return all;
    return all.filter(c => c.estadoCiclo === filter);
  }, [all, filter]);

  // KPIs derivados
  const total = all.length;
  const cumplidos = all.filter(c => c.estado === 'ok').length;
  const parciales = all.filter(c => c.estado === 'partial').length;
  const noCump = all.filter(c => c.estado === 'bad').length;
  const proximos = all.filter(c => c.d >= 0 && c.d <= 7).length;

  // Hay devoluciones?
  const devoluciones = all.filter(c => c.estadoCiclo === 'returned');

  return (
    <div data-screen-label="02 Mis Compromisos">
      {/* Header */}
      <div className="page-head">
        <div>
          <div className="page-head__eyebrow">{user.org}</div>
          <h1 className="page-head__title">Mis Compromisos Asignados</h1>
          <p className="page-head__sub">
            {total} recomendaciones internacionales bajo responsabilidad de tu institución.
            Carga avances, adjunta evidencias y atiende las observaciones de la CGR.
          </p>
        </div>
        <div className="page-head__actions">
          <button type="button" className="btn btn--ghost">
            <I.Download size={14} /> Exportar mi cartera
          </button>
          <button type="button" className="btn btn--secondary">
            <I.MessageSquare size={14} /> Consultar a la CGR
          </button>
        </div>
      </div>

      {/* Banner: devolución pendiente (HU.2.3) */}
      {devoluciones.length > 0 && (
        <div className="alert-banner alert-banner--warn">
          <div className="alert-banner__icon"><I.AlertCircle size={20} /></div>
          <div className="alert-banner__body">
            <strong>{devoluciones.length} reporte devuelto para ajuste</strong>
            <p>
              <span className="mono">{devoluciones[0].id}</span> — {devoluciones[0].text}.
              Observación de <strong>{devoluciones[0].observador}</strong> · {devoluciones[0].obsFecha}.
            </p>
          </div>
          <button type="button" className="btn btn--primary" onClick={() => onCargar(devoluciones[0].id)}>
            Atender observación <I.ArrowRight size={14} />
          </button>
        </div>
      )}

      {/* KPI strip */}
      <div className="compkpi-row">
        <div className="compkpi">
          <div className="compkpi__icon"><I.ListChecks size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{total}</div>
            <div className="compkpi__label">Compromisos asignados</div>
            <div className="compkpi__sub">{cumplidos} cumpl. · {parciales} parc. · {noCump} no cumpl.</div>
          </div>
        </div>
        <div className="compkpi is-warn">
          <div className="compkpi__icon"><I.Clock size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{proximos}</div>
            <div className="compkpi__label">Plazos próximos (D-7)</div>
            <div className="compkpi__sub">Requieren acción esta semana</div>
          </div>
        </div>
        <div className="compkpi is-danger">
          <div className="compkpi__icon"><I.AlertCircle size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{counts.returned || 0}</div>
            <div className="compkpi__label">Devueltos para ajuste</div>
            <div className="compkpi__sub">Editar lo observado</div>
          </div>
        </div>
        <div className="compkpi">
          <div className="compkpi__icon"><I.Upload size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{counts.in_review || 0}</div>
            <div className="compkpi__label">En revisión por CGR</div>
            <div className="compkpi__sub">Esperando validación</div>
          </div>
        </div>
        <div className="compkpi is-ok">
          <div className="compkpi__icon"><I.CheckCircle2 size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{counts.approved || 0}</div>
            <div className="compkpi__label">Aprobados</div>
            <div className="compkpi__sub">Ciclo cerrado por CGR</div>
          </div>
        </div>
      </div>

      {/* Tabs por estado de ciclo */}
      <div className="ciclo-tabs">
        <CicloTab id="todos"     count={counts.todos}            active={filter} onSet={setFilter}>Todos</CicloTab>
        <CicloTab id="pending"   count={counts.pending}   tone="pending"  active={filter} onSet={setFilter}>Pendientes de cargar</CicloTab>
        <CicloTab id="returned"  count={counts.returned}  tone="returned" active={filter} onSet={setFilter}>Devueltos para ajuste</CicloTab>
        <CicloTab id="draft"     count={counts.draft}     tone="draft"    active={filter} onSet={setFilter}>Borradores</CicloTab>
        <CicloTab id="in_review" count={counts.in_review} tone="review"   active={filter} onSet={setFilter}>En revisión</CicloTab>
        <CicloTab id="approved"  count={counts.approved}  tone="approved" active={filter} onSet={setFilter}>Aprobados</CicloTab>
        <CicloTab id="overdue"   count={counts.overdue}   tone="overdue"  active={filter} onSet={setFilter}>Vencidos</CicloTab>
        <div className="ciclo-tabs__spacer"></div>
        <div className="view-toggle">
          <button type="button" className={view === 'cards' ? 'is-active' : ''} onClick={() => setView('cards')}>
            <I.LayoutDashboard size={13} /> Tarjetas
          </button>
          <button type="button" className={view === 'tabla' ? 'is-active' : ''} onClick={() => setView('tabla')}>
            <I.ListChecks size={13} /> Tabla
          </button>
        </div>
      </div>

      {/* Cards / lista */}
      {view === 'cards' ? (
        <div className="mc-grid">
          {filtered.map(c => (
            <MisCompromisoCard key={c.id} c={c} onOpen={onOpenDetalle} onCargar={onCargar} />
          ))}
        </div>
      ) : (
        <div className="card table-card">
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Recomendación</th>
                  <th>Estado del ciclo</th>
                  <th>Vence</th>
                  <th>Estado cumplim.</th>
                  <th>Último avance</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(c => {
                  const meta = window.cicloMeta(c.estadoCiclo);
                  const dCls = c.d < 0 ? 'is-overdue' : c.d <= 3 ? 'is-soon' : '';
                  return (
                    <tr key={c.id} onClick={() => onOpenDetalle(c.id)}>
                      <td className="mono">{c.id}</td>
                      <td className="cell-title">
                        {c.text}
                        <div className="cell-meta">
                          <span><span className={`mech-tag mech-tag--${c.mecanismo.toLowerCase()}`}>{c.mecanismo}</span> · {c.ronda}</span>
                          <span>· Rol: {c.rol}</span>
                        </div>
                      </td>
                      <td><CicloPill ciclo={c.estadoCiclo} /></td>
                      <td className="mono">
                        {c.plazo}
                        <div className={`cell-sub ${dCls}`}>{c.d < 0 ? `D+${Math.abs(c.d)}` : c.d === 0 ? 'Hoy' : `D-${c.d}`}</div>
                      </td>
                      <td><window.StatusPill estado={c.estado} /></td>
                      <td>{c.ultimoAvance}</td>
                      <td onClick={e => e.stopPropagation()}>
                        <button type="button" className="btn btn--ghost btn--sm" onClick={() => onCargar(c.id)}>
                          {c.estadoCiclo === 'pending' || c.estadoCiclo === 'overdue' ? 'Cargar' : c.estadoCiclo === 'returned' ? 'Atender' : 'Ver'}
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------------- Card individual ----------------
function MisCompromisoCard({ c, onOpen, onCargar }) {
  const I = window.Icons;
  const meta = window.cicloMeta(c.estadoCiclo);
  const ICON = I[meta.icon];
  const isUrgent = c.d < 0 || c.estadoCiclo === 'returned' || c.estadoCiclo === 'overdue';
  const isSoon = c.d >= 0 && c.d <= 7;
  const dueText =
    c.d < 0 ? `Vencido hace ${Math.abs(c.d)} día${Math.abs(c.d) !== 1 ? 's' : ''}` :
    c.d === 0 ? 'Vence hoy' :
    c.d <= 7 ? `Vence en ${c.d} día${c.d !== 1 ? 's' : ''}` :
    `Vence el ${c.plazo}`;

  const ctaLabel =
    c.estadoCiclo === 'pending' || c.estadoCiclo === 'overdue' ? 'Cargar avance' :
    c.estadoCiclo === 'returned' ? 'Atender observación' :
    c.estadoCiclo === 'draft' ? 'Continuar borrador' :
    c.estadoCiclo === 'in_review' ? 'Ver avance enviado' :
    'Ver detalle';

  return (
    <article className={`mc-card mc-card--${meta.tone}`}>
      <div className="mc-card__top">
        <div className="mc-card__id">
          <span className={`mech-tag mech-tag--${c.mecanismo.toLowerCase()}`}>{c.mecanismo}</span>
          <span className="mono">{c.id}</span>
          <small>· {c.ronda}</small>
        </div>
        <window.StatusPill estado={c.estado} />
      </div>

      <button type="button" className="mc-card__title" onClick={() => onOpen(c.id)}>
        {c.text}
      </button>

      <div className="mc-card__ciclo">
        <span className={`ciclo-pill ciclo-pill--${meta.tone}`}>
          <ICON size={12} />
          {meta.label}
        </span>
        <span className="mc-card__rol">
          <I.Users size={11} /> Rol: <strong>{c.rol}</strong>
          {c.lider !== '—' && c.rol !== 'Líder' && <span className="muted"> · Líder: {c.lider}</span>}
        </span>
      </div>

      {/* Observación destacada si está devuelto */}
      {c.estadoCiclo === 'returned' && c.observacion && (
        <div className="obs-card">
          <div className="obs-card__head">
            <I.AlertCircle size={13} />
            <strong>Observación de la CGR</strong>
            <small>· {c.obsFecha}</small>
          </div>
          <p>{c.observacion}</p>
          <small className="muted">{c.observador}</small>
        </div>
      )}

      <div className="mc-card__meta">
        <div className={`mc-card__date${isUrgent ? ' is-urgent' : isSoon ? ' is-soon' : ''}`}>
          <I.Clock size={12} /> {dueText}
        </div>
        <div className="mc-card__stats">
          <span title="Avances cargados"><I.Upload size={11} /> {c.avances}</span>
          <span title="Evidencias adjuntas"><I.FileText size={11} /> {c.evidencias}</span>
          <span title="Último movimiento" className="muted">· {c.ultimoAvance}</span>
        </div>
      </div>

      <div className="mc-card__actions">
        <button
          type="button"
          className={`btn ${c.estadoCiclo === 'returned' || c.estadoCiclo === 'pending' || c.estadoCiclo === 'overdue' ? 'btn--primary' : 'btn--secondary'} btn--sm`}
          onClick={() => onCargar(c.id)}
        >
          {c.estadoCiclo === 'returned' ? <I.AlertCircle size={13} /> : <I.Upload size={13} />}
          {ctaLabel}
        </button>
        <button type="button" className="btn btn--ghost btn--sm" onClick={() => onOpen(c.id)}>
          <I.Eye size={13} /> Ver historial
        </button>
      </div>
    </article>
  );
}

// ---------------- Tab pill (filter) ----------------
function CicloTab({ id, count, tone, active, onSet, children }) {
  return (
    <button
      type="button"
      className={`ciclo-tab${active === id ? ' is-active' : ''}${tone ? ' ciclo-tab--' + tone : ''}`}
      onClick={() => onSet(id)}
    >
      {tone && <span className={`ciclo-tab__dot ciclo-tab__dot--${tone}`}></span>}
      <span>{children}</span>
      {count != null && <span className="ciclo-tab__count">{count}</span>}
    </button>
  );
}

// ---------------- Pill compacta ciclo ----------------
function CicloPill({ ciclo }) {
  const I = window.Icons;
  const meta = window.cicloMeta(ciclo);
  const ICON = I[meta.icon];
  return (
    <span className={`ciclo-pill ciclo-pill--${meta.tone}`}>
      <ICON size={12} /> {meta.label}
    </span>
  );
}

Object.assign(window, { MisCompromisosScreen, CicloPill });
