"use client";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import {
  deleteAdminPendingResultBatch,
  postAdminPublishResultBatch,
} from "@/api/admin-draws";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useConfirmAction } from "@/hooks/use-confirm-action";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { useAdminProfile } from "@/stores/admin-session";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminDrawBatchRow } from "@/types/api/admin-draws";

import { drawPrizeTypeLabel, drawStatusLabel } from "./draw-display";
import { PRD_DRAW_RESULT_MANAGE } from "./draw-prd";

type DrawPublishPanelProps = {
  drawId: number;
  batch: AdminDrawBatchRow;
  onPublished: () => void;
  onDiscarded: () => void;
};

export function DrawPublishPanel({
  drawId,
  batch,
  onPublished,
  onDiscarded,
}: DrawPublishPanelProps): React.ReactElement {
  const { t } = useTranslation(["draws", "common"]);
  const profile = useAdminProfile();
  const canManageDraw = adminHasAnyPermission(profile?.permissions, [PRD_DRAW_RESULT_MANAGE]);
  const [publishing, setPublishing] = useState(false);
  const [discarding, setDiscarding] = useState(false);
  const { request: requestConfirm, ConfirmDialog } = useConfirmAction();

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

  async function discardBatch(): Promise<void> {
    setDiscarding(true);
    try {
      await deleteAdminPendingResultBatch(drawId, batch.id);
      toast.success(t("discardPendingBatchSuccess"));
      onDiscarded();
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("discardPendingBatchFailed"));
    } finally {
      setDiscarding(false);
    }
  }

  async function publish(): Promise<void> {
    setPublishing(true);
    try {
      const res = await postAdminPublishResultBatch(drawId, batch.id);
      toast.success(
        t("publishSuccess", {
          drawNo: res.draw_no,
          status: drawStatusLabel(res.status, t),
        }),
      );
      onPublished();
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("publishFailed"));
    } finally {
      setPublishing(false);
    }
  }

  return (
    <div className="space-y-4">
      <div className="admin-table-shell overflow-x-auto rounded-md 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>

      {canPublish ? (
        <div className="flex flex-wrap justify-end gap-2">
          <Button
            type="button"
            variant="outline"
            size="sm"
            disabled={publishing || discarding}
            onClick={() =>
              requestConfirm({
                title: t("confirm.discardPendingBatchTitle"),
                description: t("confirm.discardPendingBatchDescription"),
                confirmVariant: "destructive",
                onConfirm: () => discardBatch(),
              })
            }
          >
            {discarding ? t("discardingPendingBatch") : t("discardPendingBatch")}
          </Button>
          <Button
            type="button"
            size="sm"
            disabled={publishing || discarding}
            onClick={() =>
              requestConfirm({
                title: t("confirm.publishTitle"),
                description: t("confirm.publishDescription"),
                confirmVariant: "destructive",
                onConfirm: () => publish(),
              })
            }
          >
            {publishing ? t("submitting") : t("confirmPublish")}
          </Button>
        </div>
      ) : (
        <p className="text-sm text-muted-foreground">{t("noPublishPermission")}</p>
      )}
      <ConfirmDialog />
    </div>
  );
}