"use client";

import Link from "next/link";
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 { getAdminTicketItem } from "@/api/admin-ticket-detail";
import { AdminListPaginationFooter } from "@/components/admin/admin-list-pagination-footer";
import { AdminStatusBadge } from "@/components/admin/admin-status-badge";
import { AdminTableExportButton } from "@/components/admin/admin-table-export-button";
import { PlayerFundingModeBadge } from "@/components/admin/player-funding-badges";
import { buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { AdminTableLoadingRow } 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 { useAdminPlayCodeLabel } from "@/hooks/use-admin-play-type-catalog";
import { useExportLabels } from "@/hooks/use-export-labels";
import { adminPlayerDetailPath } from "@/lib/admin-player-paths";
import { formatAdminMinorUnits } from "@/lib/money";
import { cn } from "@/lib/utils";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminTicketItemDetail } from "@/types/api/admin-tickets";

function ticketStatusText(value: string, t: (key: string) => string): string {
  const key = `statusOptions.${value}`;
  const translated = t(key);
  return translated === key ? value : translated;
}

export function TicketDetailConsole({ ticketNo }: { ticketNo: string }) {
  const { t } = useTranslation(["tickets", "common"]);
  const tRef = useTranslationRef(["tickets", "common"]);
  const playCodeLabel = useAdminPlayCodeLabel();
  const formatDt = useAdminDateTimeFormatter();
  const exportLabels = useExportLabels("ticketCombinations");
  const [data, setData] = useState<AdminTicketItemDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [comboPage, setComboPage] = useState(1);
  const [comboPerPage, setComboPerPage] = useState(20);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const d = await getAdminTicketItem(ticketNo);
      setData(d);
    } catch (e) {
      const msg = e instanceof LotteryApiBizError ? e.message : tRef.current("detailLoadFailed");
      setError(msg);
      setData(null);
    } finally {
      setLoading(false);
    }
  }, [ticketNo, tRef]);

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

  const combinations = useMemo(() => data?.combinations ?? [], [data?.combinations]);
  const comboLastPage = Math.max(1, Math.ceil(combinations.length / comboPerPage));
  const comboPageSafe = Math.min(comboPage, comboLastPage);
  const comboSlice = useMemo(() => {
    const start = (comboPageSafe - 1) * comboPerPage;
    return combinations.slice(start, start + comboPerPage);
  }, [combinations, comboPageSafe, comboPerPage]);

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

  const currencyCode = data?.currency_code ?? "NPR";

  return (
    <div className="flex flex-col gap-4">
      <Card>
        <CardHeader className="space-y-2">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <CardTitle className="text-lg">{t("detailTitle")}</CardTitle>
            <Link href="/admin/tickets" className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
              {t("backToList")}
            </Link>
          </div>
          <CardDescription className="font-mono text-xs">
            {data?.ticket_no ?? ticketNo}
            {data?.order_no ? ` · ${data.order_no}` : ""}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-3 text-sm">
          {loading && !data ? (
            <p className="text-muted-foreground">{t("loadingDetail")}</p>
          ) : data ? (
            <div className="grid gap-2 sm:grid-cols-2">
              <p>
                <span className="text-muted-foreground">{t("drawNo")}：</span>
                <span className="font-mono font-medium">{data.draw_no ?? "—"}</span>
              </p>
              <p>
                <span className="text-muted-foreground">{t("playCode")}：</span>
                <span>{playCodeLabel(data.play_code)}</span>
              </p>
              <p>
                <span className="text-muted-foreground">{t("number")}：</span>
                <span className="font-mono font-medium">{data.original_number ?? "—"}</span>
              </p>
              <p>
                <span className="text-muted-foreground">{t("combinationCount")}：</span>
                <span className="font-semibold tabular-nums">{data.combination_count}</span>
              </p>
              <p>
                <span className="text-muted-foreground">{t("betAmount")}：</span>
                <span className="font-semibold tabular-nums">{data.total_bet_amount_formatted}</span>
              </p>
              <p>
                <span className="text-muted-foreground">{t("actualDeduct")}：</span>
                <span className="font-semibold tabular-nums">{data.actual_deduct_amount_formatted}</span>
              </p>
              <p className="flex flex-wrap items-center gap-2">
                <span className="text-muted-foreground">{t("status")}：</span>
                <AdminStatusBadge status={data.status}>{ticketStatusText(data.status, t)}</AdminStatusBadge>
              </p>
              <p className="flex flex-wrap items-center gap-2">
                <span className="text-muted-foreground">{t("player", { ns: "tickets" })}：</span>
                <PlayerFundingModeBadge row={data} />
                {data.player_id ? (
                  <Link href={adminPlayerDetailPath(data.player_id)} className="font-mono text-xs text-primary hover:underline">
                    {data.username ?? data.site_player_id ?? data.player_id}
                  </Link>
                ) : (
                  "—"
                )}
              </p>
              <p>
                <span className="text-muted-foreground">{t("placedAt")}：</span>
                <span>{data.placed_at ? formatDt(data.placed_at) : "—"}</span>
              </p>
              {data.fail_reason_text || data.fail_reason_code ? (
                <p className="sm:col-span-2 text-destructive">
                  <span className="text-muted-foreground">{t("failReason")}：</span>
                  {data.fail_reason_text ?? data.fail_reason_code}
                </p>
              ) : null}
            </div>
          ) : null}
        </CardContent>
      </Card>

      <Card className="admin-list-card">
        <CardHeader className="admin-list-header">
          <CardTitle className="admin-list-title">{t("combinationsTitle")}</CardTitle>
          <CardDescription className="text-xs">{t("combinationsHint")}</CardDescription>
        </CardHeader>
        <CardContent className="admin-list-content">
          <div className="admin-list-actions mb-3 justify-end">
            <AdminTableExportButton
              tableId={`ticket-combinations-${ticketNo}`}
              filename={exportLabels.filename}
              sheetName={exportLabels.sheetName}
            />
          </div>
          <div className="admin-table-shell">
            <Table id={`ticket-combinations-${ticketNo}`}>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-16 text-center">No.</TableHead>
                  <TableHead>{t("number4d")}</TableHead>
                  <TableHead className="text-center">{t("comboBetAmount")}</TableHead>
                  <TableHead className="text-center">{t("comboEstimatedPayout")}</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading && !data ? <AdminTableLoadingRow colSpan={4} /> : null}
                {comboSlice.map((row) => (
                  <TableRow key={`${row.combination_no}-${row.number_4d}`}>
                    <TableCell className="text-center font-mono text-xs">{row.combination_no}</TableCell>
                    <TableCell className="font-mono font-medium">{row.number_4d}</TableCell>
                    <TableCell className="text-center tabular-nums text-sm">
                      {formatAdminMinorUnits(row.bet_amount, currencyCode)}
                    </TableCell>
                    <TableCell className="text-center tabular-nums text-sm">
                      {formatAdminMinorUnits(row.estimated_payout, currencyCode)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          {combinations.length > 0 ? (
            <AdminListPaginationFooter
              selectId={`ticket-combo-${ticketNo}`}
              total={combinations.length}
              page={comboPageSafe}
              lastPage={comboLastPage}
              perPage={comboPerPage}
              loading={loading}
              onPerPageChange={(n) => {
                setComboPerPage(n);
                setComboPage(1);
              }}
              onPageChange={setComboPage}
            />
          ) : null}
        </CardContent>
      </Card>
    </div>
  );
}
