// app/admin/draw/page.tsx
// The draw stepper page (server component). Gates on draw_officer, loads the
// raffle list for selection, and the chosen raffle's draw state, then renders the
// client stepper with the reconciliation server action wired in.
//
// Selection: ?raffle=<id>. With no raffle chosen, show a picker. The admin layout
// already gates the /admin tree at viewer; the draw is a restricted action, so we
// re-gate here at draw_officer (defence in depth + correct 403 copy).

import * as React from "react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { requireRole, AuthError } from "@/lib/auth";
import { listRaffles } from "@/app/admin/_lib/queries";
import { Card, Badge } from "@/components/ui";
import { loadDrawStepperState } from "./_lib/state";
import { checkReconciliation } from "./_lib/actions";
import { DrawStepper } from "./DrawStepper";

export const dynamic = "force-dynamic";

export default async function DrawPage({
  searchParams,
}: {
  searchParams: Promise<{ raffle?: string }>;
}) {
  try {
    await requireRole("draw_officer");
  } catch (err) {
    if (err instanceof AuthError) {
      if (err.status === 401) redirect("/admin/login");
      // 403: authenticated but under-roled. Show a clear message, not the stepper.
      return (
        <Card elevation="drop">
          <h1 className="font-impact text-heading-lg font-bold text-ink-strong">
            Sorteo
          </h1>
          <p className="mt-2 font-body text-body-md text-ink-strong">
            No tienes permisos para ejecutar el sorteo. Esta acción está
            restringida al rol de oficial de sorteo (draw officer).
          </p>
        </Card>
      );
    }
    throw err;
  }

  const { raffle: raffleId } = await searchParams;

  if (!raffleId) {
    const raffles = await listRaffles();
    return (
      <div className="flex flex-col gap-md">
        <h1 className="font-impact text-heading-lg font-bold text-ink-strong">
          Sorteo
        </h1>
        <p className="font-body text-body-md text-muted">
          Elige la rifa que vas a sortear. El sorteo sigue un proceso guiado de
          solo avance: pre-vuelo, comprometer, revelar y verificar.
        </p>
        <Card elevation="drop" as="section">
          <h2 className="font-display text-heading-md font-bold text-ink-strong">
            Rifas
          </h2>
          {raffles.length === 0 ? (
            <p className="mt-2 font-body text-body-md text-muted">
              No hay rifas configuradas.
            </p>
          ) : (
            <ul className="mt-md flex flex-col gap-2">
              {raffles.map((r) => (
                <li key={r.id}>
                  <Link
                    href={`/admin/draw?raffle=${r.id}`}
                    className="flex min-h-[44px] items-center justify-between rounded-md border border-hairline px-md py-2 font-body text-body-md text-ink-strong hover:border-primary"
                  >
                    <span>{r.name}</span>
                    <Badge tone={r.status === "closed" ? "blue" : "neutral"}>
                      {r.status}
                    </Badge>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </Card>
      </div>
    );
  }

  const state = await loadDrawStepperState(raffleId);

  return (
    <div className="flex flex-col gap-md">
      <Link
        href="/admin/draw"
        className="inline-flex min-h-[44px] items-center font-body text-body-md font-bold text-steelblue underline"
      >
        Cambiar de rifa
      </Link>
      <DrawStepper initial={state} checkReconciliation={checkReconciliation} />
    </div>
  );
}
