"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 { getAdminRiskPoolDetail } from "@/api/admin-risk";
import { AdminListPaginationFooter } from "@/components/admin/admin-list-pagination-footer";
import { AdminTableExportButton } from "@/components/admin/admin-table-export-button";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { AdminLoadingState, AdminLoadingInline, AdminTableLoadingRow } from "@/components/admin/admin-loading-state";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useAdminCurrencyCatalog } from "@/hooks/use-admin-currency-catalog";
import { useAdminPlayCodeLabel } from "@/hooks/use-admin-play-type-catalog";
import { useExportLabels } from "@/hooks/use-export-labels";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { riskActionTypeLabel, riskSourceReasonLabel } from "@/modules/risk/risk-display";
import { formatAdminMinorUnits } from "@/lib/money";
import { cn } from "@/lib/utils";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminRiskPoolDetailLogRow, AdminRiskPoolShowData } from "@/types/api/admin-risk";

export function RiskPoolDetailConsole({
  drawId,
  number4d,
}: {
  drawId: number;
  number4d: string;
}) {
  const { t } = useTranslation(["risk", "common"]);
  const tRef = useTranslationRef(["risk", "common"]);
  const exportLabels = useExportLabels("riskPoolDetail", { number: number4d });
  useAdminCurrencyCatalog();
  const playCodeLabel = useAdminPlayCodeLabel();
  const formatDt = useAdminDateTimeFormatter();
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(10);
  const [data, setData] = useState<AdminRiskPoolShowData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const d = await getAdminRiskPoolDetail(drawId, number4d, { page, per_page: perPage });
      setData(d);
    } catch (e) {
      const msg =
        e instanceof LotteryApiBizError ? e.message : tRef.current("loadDetailFailed");
      setError(msg);
      setData(null);
    } finally {
      setLoading(false);
    }
  }, [drawId, number4d, page, perPage]);

  useAsyncEffect(() => {
    void load();
  }, [drawId, number4d, page, perPage]);

  if (error && !data) {
    return (
        <Card className="border-destructive/40">
        <CardHeader>
          <CardTitle className="text-lg">{t("detailTitle")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2">
          <p className="text-sm text-destructive">{error}</p>
          <Link
            href={`/admin/draws/${drawId}/risk/pools`}
            className={cn(buttonVariants({ variant: "outline", size: "sm" }))}
          >
            {t("backToList")}
          </Link>
        </CardContent>
      </Card>
    );
  }

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

  if (!data) {
    return null;
  }

  const { pool, logs } = data;
  const currencyCode = data.currency_code ?? "NPR";

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

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">
            {t("numberTitle", { number: pool.normalized_number })}
          </CardTitle>
          <p className="text-sm text-muted-foreground">{t("drawMeta", { drawNo: data.draw_no })}</p>
        </CardHeader>
        <CardContent className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <div className="rounded-lg border bg-muted/40 p-3">
            <p className="text-xs text-muted-foreground">{t("totalCap")}</p>
            <p className="mt-1 text-2xl font-semibold leading-none tracking-tight">
              {formatAdminMinorUnits(pool.total_cap_amount, currencyCode)}
            </p>
          </div>
          <div className="rounded-lg border bg-muted/40 p-3">
            <p className="text-xs text-muted-foreground">{t("lockedWorstCase")}</p>
            <p className="mt-1 text-2xl font-semibold leading-none tracking-tight">
              {formatAdminMinorUnits(pool.locked_amount, currencyCode)}
            </p>
          </div>
          <div className="rounded-lg border bg-muted/40 p-3">
            <p className="text-xs text-muted-foreground">{t("remainingSellable")}</p>
            <p className="mt-1 text-2xl font-semibold leading-none tracking-tight">
              {formatAdminMinorUnits(pool.remaining_amount, currencyCode)}
            </p>
          </div>
          <div className="rounded-lg border bg-muted/40 p-3">
            <p className="text-xs text-muted-foreground">{t("isSoldOut")}</p>
            <p className="mt-1 text-sm font-medium">{pool.is_sold_out ? t("yes") : t("no")}</p>
            <p className="mt-0.5 text-xs text-muted-foreground">
              {t("usageRatio")}{" "}
              {pool.usage_ratio != null ? `${(pool.usage_ratio * 100).toFixed(2)}%` : "—"}
            </p>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("occupationLogs")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="overflow-x-auto rounded-md border">
            <div className="admin-table-toolbar">
              <AdminTableExportButton
                tableId={`risk-pool-detail-table-${drawId}-${number4d}`}
                filename={exportLabels.filename}
                sheetName={exportLabels.sheetName}
              />
            </div>
            <Table id={`risk-pool-detail-table-${drawId}-${number4d}`}>
              <TableHeader>
                <TableRow>
                  <TableHead>{t("time")}</TableHead>
                  <TableHead>{t("action")}</TableHead>
                  <TableHead className="text-center">{t("amount")}</TableHead>
                  <TableHead>{t("source")}</TableHead>
                  <TableHead>{t("ticketNo")}</TableHead>
                  <TableHead>{t("playCode")}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {logs.items.map((row: AdminRiskPoolDetailLogRow) => (
                  <TableRow key={row.id}>
                    <TableCell className="whitespace-nowrap text-xs text-muted-foreground">
                      {row.created_at ? formatDt(row.created_at) : "—"}
                    </TableCell>
                    <TableCell className="text-sm">{riskActionTypeLabel(row.action_type, t)}</TableCell>
                    <TableCell className="text-center text-sm font-semibold">
                      {formatAdminMinorUnits(row.amount, currencyCode)}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {riskSourceReasonLabel(row.source_reason, t)}
                    </TableCell>
                    <TableCell className="font-mono text-xs">{row.ticket_no ?? "—"}</TableCell>
                    <TableCell className="text-xs">{playCodeLabel(row.play_code)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          <AdminListPaginationFooter
            selectId={`risk-pool-detail-${drawId}-${number4d}`}
            total={logs.meta.total}
            page={logs.meta.current_page}
            lastPage={logs.meta.last_page}
            perPage={logs.meta.per_page}
            loading={loading}
            onPerPageChange={(n) => {
              setPerPage(n);
              setPage(1);
            }}
            onPageChange={setPage}
          />
        </CardContent>
      </Card>
    </div>
  );
}
