"use client";

import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { useTranslationRef } from "@/hooks/use-translation-ref";

import { getAdminDrawResultBatches } from "@/api/admin-draws";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { AdminNoResourceState } from "@/components/admin/admin-no-resource-state";
import { AdminLoadingState } from "@/components/admin/admin-loading-state";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminDrawBatchRow, AdminDrawBatchesData } from "@/types/api/admin-draws";

import { drawPrizeTypeLabel } from "./draw-display";

export function DrawResultsConsole({ drawId }: { drawId: string }) {
  const { t } = useTranslation(["draws", "common"]);
  const tRef = useTranslationRef(["draws", "common"]);
  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(tRef.current("invalidDrawId"));
      setLoading(false);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      setData(await getAdminDrawResultBatches(idNum));
    } catch (e) {
      setData(null);
      setError(e instanceof LotteryApiBizError ? e.message : tRef.current("errors.loadFailed", { ns: "common" }));
    } finally {
      setLoading(false);
    }
  }, [idNum, tRef]);

  useAsyncEffect(() => {
    void load();
  }, [idNum]);

  if (loading && !data) {
    return <AdminLoadingState minHeight="6rem" className="py-6" />;
  }

  if (error) {
    return <p className="text-sm text-destructive">{error}</p>;
  }
  if (!data) {
    return <AdminNoResourceState />;
  }

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

  return (
    <div className="space-y-4">
      {published.length === 0 ? (
        <AdminNoResourceState message={t("noPublishedBatch")} />
      ) : (
        published.map((batch) => (
          <BatchTable key={batch.id} batch={batch} />
        ))
      )}
    </div>
  );
}

function BatchTable({ batch }: { batch: AdminDrawBatchRow }) {
  const { t } = useTranslation("draws");
  const formatDt = useAdminDateTimeFormatter();
  return (
    <Card>
      <CardHeader className="flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm">{t("version", { version: batch.result_version })}</CardTitle>
        <p className="font-mono text-xs text-muted-foreground">
          {formatDt(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>
  );
}
