// components/admin/ParticipantTable.tsx
// Client table for participants. PII shows masked; an operator+ can reveal a
// row's contact, which calls logUnmaskAction (server, writes the audit log) and
// only then swaps the displayed value to the raw one already provided to the
// operator-role payload. Accessible: semantic table, button reveals, status text.

"use client";

import * as React from "react";
import Link from "next/link";
import { logUnmaskAction } from "@/app/admin/_lib/actions";
import { formatPEN } from "@/lib/money";

export interface ParticipantTableRow {
  id: string;
  fullName: string;
  phoneMasked: string;
  emailMasked: string;
  phoneRaw: string | null;
  emailRaw: string | null;
  marketingConsent: boolean;
  chancesThisRaffle: number;
  paidPurchases: number;
  totalPaidCents: number;
  createdAt: string;
}

export function ParticipantTable({
  rows,
  canUnmask,
  raffleId,
}: {
  rows: ParticipantTableRow[];
  canUnmask: boolean;
  raffleId: string;
}) {
  const [revealed, setRevealed] = React.useState<Record<string, boolean>>({});
  const [pending, setPending] = React.useState<string | null>(null);

  async function reveal(id: string) {
    if (!canUnmask) return;
    setPending(id);
    const res = await logUnmaskAction(raffleId, id);
    setPending(null);
    if (res.ok) {
      setRevealed((prev) => ({ ...prev, [id]: true }));
    }
  }

  if (rows.length === 0) {
    return (
      <p className="font-body text-body-md text-muted">
        No se encontraron participantes.
      </p>
    );
  }

  return (
    <div className="overflow-x-auto">
      <table className="w-full border-collapse text-left">
        <caption className="sr-only">
          Participantes del sorteo, con datos de contacto enmascarados por defecto
        </caption>
        <thead>
          <tr className="border-b border-hairline">
            <Th>Nombre</Th>
            <Th>Teléfono</Th>
            <Th>Correo</Th>
            <Th>Oportunidades</Th>
            <Th>Compras</Th>
            <Th>Pagó</Th>
            <Th>Total pagado</Th>
            <Th>Marketing</Th>
            <Th>Registrado</Th>
            {canUnmask ? <Th>Acción</Th> : null}
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => {
            const isRevealed = revealed[r.id];
            return (
              <tr key={r.id} className="border-b border-hairline last:border-0">
                <Td>
                  <Link
                    href={`/admin/participantes/${r.id}?raffle=${raffleId}`}
                    className="font-medium text-steelblue underline-offset-2 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-steelblue"
                  >
                    {r.fullName}
                  </Link>
                </Td>
                <Td>
                  {isRevealed && r.phoneRaw ? r.phoneRaw : r.phoneMasked}
                </Td>
                <Td>
                  {isRevealed && r.emailRaw ? r.emailRaw : r.emailMasked}
                </Td>
                <Td>{r.chancesThisRaffle.toLocaleString("es-PE")}</Td>
                <Td>{r.paidPurchases.toLocaleString("es-PE")}</Td>
                <Td>{r.paidPurchases > 0 ? "Sí" : "No"}</Td>
                <Td>{formatPEN(r.totalPaidCents)}</Td>
                <Td>{r.marketingConsent ? "Sí" : "No"}</Td>
                <Td>{new Date(r.createdAt).toLocaleDateString("es-PE")}</Td>
                {canUnmask ? (
                  <Td>
                    {isRevealed ? (
                      <span className="font-body text-caption text-muted">
                        Revelado (registrado)
                      </span>
                    ) : (
                      <button
                        type="button"
                        onClick={() => reveal(r.id)}
                        disabled={pending === r.id}
                        className="min-h-11 rounded-md border border-steelblue px-3 font-body text-caption font-medium text-steelblue hover:bg-steelblue hover:text-on-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-steelblue disabled:opacity-50"
                      >
                        {pending === r.id ? "Registrando..." : "Revelar datos"}
                      </button>
                    )}
                  </Td>
                ) : null}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function Th({ children }: { children: React.ReactNode }) {
  return (
    <th
      scope="col"
      className="py-2 pr-4 font-body text-caption font-medium text-muted-label"
    >
      {children}
    </th>
  );
}
function Td({ children }: { children: React.ReactNode }) {
  return (
    <td className="py-2 pr-4 font-body text-body-md text-ink-strong">
      {children}
    </td>
  );
}
