"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { getAdminDrawResultBatches } from "@/api/admin-draws";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { cn } from "@/lib/utils";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { useAdminProfile } from "@/stores/admin-session";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminDrawBatchRow, AdminDrawBatchesData } from "@/types/api/admin-draws";

import { drawPrizeTypeLabel } from "./draw-display";
import { PRD_DRAW_RESULT_MANAGE } from "./draw-prd";
import { DrawStatusBadge } from "./draw-status-badge";

export function DrawResultsConsole({ drawId }: { drawId: string }) {
  const { t } = useTranslation(["draws", "common"]);
  const profile = useAdminProfile();
  const canManageDraw = adminHasAnyPermission(profile?.permissions, [
    PRD_DRAW_RESULT_MANAGE,
  ]);
  const idNum = Number(drawId);
  const [data, setData] = useState<AdminDrawBatchesData | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    if (!Number.isFinite(idNum)) {
      setError(t("invalidDrawId"));
      setLoading(false);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      setData(await getAdminDrawResultBatches(idNum));
    } catch (e) {
      setData(null);
      setError(e instanceof LotteryApiBizError ? e.message : t("errors.loadFailed", { ns: "common" }));
    } finally {
      setLoading(false);
    }
  }, [idNum, t]);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void load();
    }, 0);
    return () => window.clearTimeout(timer);
  }, [load]);

  if (loading && !data) {
    return <p className="text-sm text-muted-foreground">{t("states.loading", { ns: "common" })}</p>;
  }

  if (error || !data) {
    return <p className="text-sm text-destructive">{error ?? t("states.noData", { ns: "common" })}</p>;
  }

  const published = data.batches.filter((b) => b.status === "published");

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div>
          <h2 className="text-lg font-semibold">{t("resultsTitle")}</h2>
          <p className="text-sm text-muted-foreground">
            {t("drawNo")} {data.draw_no} · <DrawStatusBadge status={data.draw_status} />
          </p>
        </div>
        <Link
          href={`/admin/draws/${drawId}/review`}
          className={cn(buttonVariants({ variant: "outline", size: "sm" }))}
        >
          {canManageDraw ? t("reviewAndPublish") : t("viewReviewQueue")}
        </Link>
      </div>

      {published.length === 0 ? (
        <Card>
          <CardContent className="py-8 text-center text-sm text-muted-foreground">
            {t("noPublishedBatch")}
          </CardContent>
        </Card>
      ) : (
        published.map((batch) => <BatchTable key={batch.id} batch={batch} />)
      )}
    </div>
  );
}

function BatchTable({ batch }: { batch: AdminDrawBatchRow }) {
  const { t } = useTranslation("draws");
  return (
    <Card>
      <CardHeader className="pb-2">
        <CardTitle className="text-base">{t("version", { version: batch.result_version })}</CardTitle>
        <p className="font-mono text-xs text-muted-foreground">
          {t("sourceType", {
            source: batch.source_type === "manual" ? t("manualEntry") : t("rng"),
          })}{" "}
          · {t("rngSummary", { hash: batch.rng_seed_hash ?? "—" })} ·{" "}
          {t("confirmedAt", { time: batch.confirmed_at ?? "—" })}
        </p>
      </CardHeader>
      <CardContent className="overflow-x-auto pt-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t("prize")}</TableHead>
              <TableHead>#</TableHead>
              <TableHead className="font-mono">4D</TableHead>
              <TableHead className="hidden sm:table-cell">{t("tail3")}</TableHead>
              <TableHead className="hidden sm:table-cell">{t("tail2")}</TableHead>
              <TableHead className="hidden md:table-cell">{t("headTail")}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {batch.items.map((it) => (
              <TableRow key={`${it.prize_type}-${it.prize_index}`}>
                <TableCell className="text-xs">
                  {drawPrizeTypeLabel(it.prize_type, it.prize_index, t)}
                </TableCell>
                <TableCell className="font-mono text-xs">{it.prize_index}</TableCell>
                <TableCell className="font-mono text-sm font-semibold">{it.number_4d}</TableCell>
                <TableCell className="hidden font-mono text-xs sm:table-cell">
                  {it.suffix_3d ?? "—"}
                </TableCell>
                <TableCell className="hidden font-mono text-xs sm:table-cell">
                  {it.suffix_2d ?? "—"}
                </TableCell>
                <TableCell className="hidden text-xs md:table-cell">
                  {it.head_digit ?? "—"} / {it.tail_digit ?? "—"}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
}
