"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { useTranslationRef } from "@/hooks/use-translation-ref";
import { toast } from "sonner";

import {
  deleteAdminPendingResultBatch,
  getAdminDrawResultBatches,
  postAdminPublishResultBatch,
} from "@/api/admin-draws";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { AdminNoResourceState } from "@/components/admin/admin-no-resource-state";
import { AdminLoadingState, AdminLoadingInline, AdminTableLoadingRow } from "@/components/admin/admin-loading-state";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useConfirmAction } from "@/hooks/use-confirm-action";
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 { drawBatchStatusLabel, drawPrizeTypeLabel, drawStatusLabel } from "./draw-display";
import { PRD_DRAW_RESULT_MANAGE } from "./draw-prd";

export function DrawPublishConsole({ drawId, batchId }: { drawId: string; batchId: string }) {
  const { t } = useTranslation(["draws", "common"]);
  const tRef = useTranslationRef(["draws", "common"]);
  const router = useRouter();
  const profile = useAdminProfile();
  const canManageDraw = adminHasAnyPermission(profile?.permissions, [
    PRD_DRAW_RESULT_MANAGE,
  ]);
  const idNum = Number(drawId);
  const batchNum = Number(batchId);
  const [data, setData] = useState<AdminDrawBatchesData | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [publishing, setPublishing] = useState(false);
  const [discarding, setDiscarding] = useState(false);
  const { request: requestConfirm, ConfirmDialog } = useConfirmAction();

  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]);

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

  const batch: AdminDrawBatchRow | undefined = useMemo(() => {
    if (!Number.isFinite(batchNum)) return undefined;
    return data?.batches.find((b) => b.id === batchNum);
  }, [batchNum, data]);

  async function discardBatch(): Promise<void> {
    if (!Number.isFinite(idNum) || !Number.isFinite(batchNum)) return;
    setDiscarding(true);
    try {
      await deleteAdminPendingResultBatch(idNum, batchNum);
      toast.success(t("discardPendingBatchSuccess"));
      router.replace(`/admin/draws/${drawId}/review`);
    } catch (e) {
      toast.error(
        e instanceof LotteryApiBizError ? e.message : t("discardPendingBatchFailed"),
      );
    } finally {
      setDiscarding(false);
    }
  }

  async function publish(): Promise<void> {
    if (!Number.isFinite(idNum) || !Number.isFinite(batchNum)) return;
    setPublishing(true);
    try {
      const res = await postAdminPublishResultBatch(idNum, batchNum);
      toast.success(
        t("publishSuccess", {
          drawNo: res.draw_no,
          status: drawStatusLabel(res.status, t),
        }),
      );
      await load();
    } catch (e) {
      const msg = e instanceof LotteryApiBizError ? e.message : t("publishFailed");
      toast.error(msg);
    } finally {
      setPublishing(false);
    }
  }

  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 />;
  }

  if (!batch) {
    return (
      <Alert variant="destructive">
        <AlertTitle>{t("batchNotFound")}</AlertTitle>
        <AlertDescription>{t("batchNotFoundDesc")}</AlertDescription>
      </Alert>
    );
  }

  const canPublish =
    canManageDraw && batch.status === "pending_review";

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <Link href={`/admin/draws/${drawId}/review`} className={buttonVariants({ variant: "ghost", size: "sm" })}>
          ← {t("backToReviewQueue")}
        </Link>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">{t("publishTitle")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {!canManageDraw ? (
            <Alert variant="destructive">
              <AlertTitle>{t("noPublishPermission")}</AlertTitle>
              <AlertDescription>{t("noPublishPermission")}</AlertDescription>
            </Alert>
          ) : null}
          {!canPublish && canManageDraw ? (
            <Alert>
              <AlertTitle>{t("cannotPublish")}</AlertTitle>
              <AlertDescription>
                {t("cannotPublishDesc", { status: drawBatchStatusLabel(batch.status, t) })}
              </AlertDescription>
            </Alert>
          ) : null}
          {canPublish ? (
            <>
              <Alert>
                <AlertTitle>{t("checkBeforePublish")}</AlertTitle>
                <AlertDescription>{t("checkBeforePublishDesc")}</AlertDescription>
              </Alert>
              <p className="text-sm text-muted-foreground">{t("publishReadOnlyHint")}</p>
            </>
          ) : null}

          <div className="overflow-x-auto rounded-lg border border-border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t("prize")}</TableHead>
                  <TableHead>#</TableHead>
                  <TableHead className="font-mono">4D</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>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          <p className="font-mono text-xs text-muted-foreground">
            {t("sourceTypeFull", {
              source: batch.source_type === "manual" ? t("manualEntry") : t("rngAutoGenerate"),
              count: batch.items.length,
              hash: batch.rng_seed_hash ?? "—",
            })}
          </p>
        </CardContent>
        <CardFooter className="flex flex-wrap justify-end gap-2">
          <Link
            href={`/admin/draws/${drawId}/results`}
            className={cn(buttonVariants({ variant: "outline", size: "default" }))}
          >
            {t("publishedView")}
          </Link>
          {canPublish ? (
            <Button
              type="button"
              variant="outline"
              disabled={publishing || discarding}
              onClick={() =>
                requestConfirm({
                  title: t("confirm.discardPendingBatchTitle"),
                  description: t("confirm.discardPendingBatchDescription"),
                  confirmVariant: "destructive",
                  onConfirm: () => discardBatch(),
                })
              }
            >
              {discarding ? t("discardingPendingBatch") : t("discardPendingBatch")}
            </Button>
          ) : null}
          <Button
            type="button"
            disabled={!canPublish || publishing || discarding}
            onClick={() =>
              requestConfirm({
                title: t("confirm.publishTitle"),
                description: t("confirm.publishDescription"),
                confirmVariant: "destructive",
                onConfirm: () => publish(),
              })
            }
          >
            {publishing ? t("submitting") : t("confirmPublish")}
          </Button>
        </CardFooter>
      </Card>
      <ConfirmDialog />
    </div>
  );
}
