"use client";

import Link from "next/link";
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 { getAdminDrawFinanceSummary } from "@/api/admin-draws";
import { postAdminRunDrawSettlement } from "@/api/admin-settlement";
import { Button, buttonVariants } from "@/components/ui/button";
import { AdminStatusBadge } from "@/components/admin/admin-status-badge";
import { AdminTableExportButton } from "@/components/admin/admin-table-export-button";

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 { adminHasAnyPermission } from "@/lib/admin-permissions";
import { signedMoneyClass } from "@/lib/admin-signed-money";
import { cn } from "@/lib/utils";
import { useAdminProfile } from "@/stores/admin-session";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminDrawFinanceSummaryData } from "@/types/api/admin-draw-finance";
import { toast } from "sonner";

import { useAdminCurrencyCatalog } from "@/hooks/use-admin-currency-catalog";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { useConfirmAction } from "@/hooks/use-confirm-action";
import { useExportLabels } from "@/hooks/use-export-labels";
import { formatAdminMinorUnits } from "@/lib/money";

import { settlementBatchStatusLabel } from "./draw-display";
import { PRD_PAYOUT_MANAGE, PRD_PAYOUT_REVIEW } from "./draw-prd";

export function DrawFinanceConsole({ drawId }: { drawId: string }): React.ReactElement {
  const { t } = useTranslation(["draws", "settlement", "common"]);
  const tRef = useTranslationRef(["draws", "settlement", "common"]);
  useAdminCurrencyCatalog();
  const idNum = Number(drawId);
  const profile = useAdminProfile();
  const canRunSettlement = adminHasAnyPermission(profile?.permissions, [
    PRD_PAYOUT_MANAGE,
    PRD_PAYOUT_REVIEW,
  ]);
  const [data, setData] = useState<AdminDrawFinanceSummaryData | null>(null);
  const formatTs = useAdminDateTimeFormatter();
  const exportLabels = useExportLabels("drawFinance", { drawNo: data?.draw_no ?? drawId });
  const [err, setErr] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [settling, setSettling] = useState(false);
  const { request: requestConfirm, ConfirmDialog } = useConfirmAction();

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

  async function runSettlement(): Promise<void> {
    if (!Number.isFinite(idNum) || idNum < 1) return;
    setSettling(true);
    try {
      const res = await postAdminRunDrawSettlement(idNum);
      toast.success(res.ran ? t("runSettlement") : t("status"));
      await load();
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("actionFailed", { name: t("runSettlement") }));
    } finally {
      setSettling(false);
    }
  }

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

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

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

  const currencyCode = data.currency_code ?? "NPR";
  const formatMoney = (minor: number) => formatAdminMinorUnits(minor, currencyCode);

  return (
    <div className="space-y-4">
      <div className="grid gap-3 text-sm sm:grid-cols-3">
        <div className="rounded-lg border border-border/60 px-3 py-2">
          <p className="text-xs text-muted-foreground">{t("orderAndItemCount")}</p>
          <p className="mt-0.5 tabular-nums font-medium">
            {data.order_count} / {data.ticket_item_count}
          </p>
        </div>
        <div className="rounded-lg border border-border/60 px-3 py-2">
          <p className="text-xs text-muted-foreground">{t("actualBet")}</p>
          <p className="mt-0.5 tabular-nums font-medium">{formatMoney(data.total_bet_minor)}</p>
        </div>
        <div className="rounded-lg border border-border/60 px-3 py-2">
          <p className="text-xs text-muted-foreground">{t("grossProfit")}</p>
          <p className={cn("mt-0.5 tabular-nums font-semibold", signedMoneyClass(data.approx_house_gross_minor, true))}>
            {formatMoney(data.approx_house_gross_minor)}
          </p>
        </div>
      </div>

      <div className="flex flex-wrap gap-2">
        <Button type="button" variant="secondary" size="sm" onClick={() => void load()}>
          {t("actions.refresh", { ns: "common" })}
        </Button>
        <Button
          type="button"
          size="sm"
          disabled={!canRunSettlement || settling || data.draw_status !== "settling"}
          onClick={() =>
            requestConfirm({
              title: t("confirm.runSettlementTitle"),
              description: t("confirm.runSettlementDescription"),
              onConfirm: () => runSettlement(),
            })
          }
        >
          {settling ? t("processing") : t("runSettlement")}
        </Button>
        <Link
          href="/admin/settlement-batches"
          className={cn(buttonVariants({ variant: "outline", size: "sm" }))}
        >
          {t("settlementBatchList")}
        </Link>
      </div>

      <div className="rounded-lg border border-border/60">
        <div className="border-b border-border/60 px-3 py-2.5">
          <h2 className="text-sm font-semibold">{t("relatedSettlementBatches")}</h2>
        </div>
        <div className="p-3">
          {data.settlement_batches.length === 0 ? (
            <AdminNoResourceState className="py-4" />
          ) : (
            <div className="overflow-x-auto rounded-md border">
              <div className="admin-table-toolbar">
                <AdminTableExportButton
                  tableId={`draw-finance-table-${drawId}`}
                  filename={exportLabels.filename}
                  sheetName={exportLabels.sheetName}
                />
              </div>
              <Table id={`draw-finance-table-${drawId}`}>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-20">{t("table.id", { ns: "common" })}</TableHead>
                    <TableHead>{t("status")}</TableHead>
                    <TableHead className="text-center">{t("ticketCount")}</TableHead>
                    <TableHead className="text-center">{t("winCount")}</TableHead>
                    <TableHead className="text-center">{t("payoutTotal")}</TableHead>
                    <TableHead className="text-center">{t("jackpotPayout")}</TableHead>
                    <TableHead>{t("finishedAt")}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {data.settlement_batches.map((b) => (
                    <TableRow key={b.id}>
                      <TableCell className="font-mono text-xs">{b.id}</TableCell>
                      <TableCell>
                        <AdminStatusBadge status={b.status}>
                          {settlementBatchStatusLabel(b.status, t)}
                        </AdminStatusBadge>
                      </TableCell>
                      <TableCell className="text-center tabular-nums text-xs">
                        {b.total_ticket_count}
                      </TableCell>
                      <TableCell className="text-center tabular-nums text-xs">
                        {b.total_win_count}
                      </TableCell>
                      <TableCell className="text-center tabular-nums text-xs">
                        {formatMoney(b.total_payout_amount)}
                      </TableCell>
                      <TableCell className="text-center tabular-nums text-xs">
                        {formatMoney(b.total_jackpot_payout_amount)}
                      </TableCell>
                      <TableCell className="whitespace-nowrap text-xs text-muted-foreground">
                        {formatTs(b.finished_at)}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </div>
      </div>
      <ConfirmDialog />
    </div>
  );
}
