"use client";

import { useCallback, useState, type ReactNode } from "react";
import { useSearchParams } from "next/navigation";
import { useExportLabels } from "@/hooks/use-export-labels";
import { useTranslation } from "react-i18next";
import { useAsyncEffect } from "@/hooks/use-async-effect";
import { useTranslationRef } from "@/hooks/use-translation-ref";

import { getAdminTicketItems } from "@/api/admin-tickets";
import { AdminDateRangeField } from "@/components/admin/admin-date-range-field";
import { AdminTableNoResourceRow } from "@/components/admin/admin-no-resource-state";
import { AdminListPaginationFooter } from "@/components/admin/admin-list-pagination-footer";
import { AdminAgentIdentityCells, AdminAgentIdentityHeads } from "@/components/admin/admin-agent-columns";
import { AdminPlayerIdentityCells, AdminPlayerIdentityHeads } from "@/components/admin/admin-player-identity-columns";
import { AdminTableExportButton } from "@/components/admin/admin-table-export-button";
import { AdminRowActionsMenu } from "@/components/admin/admin-row-actions-menu";
import { AdminStatusBadge } from "@/components/admin/admin-status-badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
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 { PlayerFundingModeBadge } from "@/components/admin/player-funding-badges";
import { adminPlayerDetailPath } from "@/lib/admin-player-paths";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminTicketItemsData } from "@/types/api/admin-tickets";
import { ChevronDown, Eye } from "lucide-react";
import Link from "next/link";

/** 与玩家端、注项表 status 字段对齐（不含无效的 success） */
const TICKET_STATUS_OPTIONS = [
  "pending_confirm",
  "partial_pending_confirm",
  "placed",
  "pending_draw",
  "partial_failed",
  "failed",
  "pending_payout",
  "settled_win",
  "settled_lose",
  "refunded",
] as const;

type TicketFilters = {
  playerQuery: string;
  drawNo: string;
  numberKeyword: string;
  startDate: string;
  endDate: string;
  statuses: string[];
};

const emptyTicketFilters: TicketFilters = {
  playerQuery: "",
  drawNo: "",
  numberKeyword: "",
  startDate: "",
  endDate: "",
  statuses: [],
};

type TicketTranslateFn = (
  key: string,
  options?: { count?: number },
) => string;

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

function ticketStatusSummary(statuses: string[], t: TicketTranslateFn): string {
  if (statuses.length === 0) {
    return t("statusOptions.all");
  }

  if (statuses.length === 1) {
    return ticketStatusText(statuses[0], t);
  }

  return t("statusSelectedCount", { count: statuses.length });
}

function ticketDetailPath(ticketNo: string): string {
  return `/admin/tickets/${encodeURIComponent(ticketNo)}`;
}

function TicketFilterField({
  id,
  label,
  children,
}: {
  id: string;
  label: string;
  children: ReactNode;
}) {
  return (
    <div className="grid min-w-0 gap-1.5">
      <Label htmlFor={id} className="text-xs font-medium text-muted-foreground">
        {label}
      </Label>
      {children}
    </div>
  );
}

export function PlayerTicketsConsole(): React.ReactElement {
  const { t } = useTranslation(["tickets", "common"]);
  const tRef = useTranslationRef(["tickets", "common"]);
  const playCodeLabel = useAdminPlayCodeLabel();
  const exportLabels = useExportLabels("tickets");
  const formatTs = useAdminDateTimeFormatter();
  const searchParams = useSearchParams();
  const playerIdFromUrl = (searchParams.get("player_id") ?? "").trim();
  const drawNoFromUrl = (searchParams.get("draw_no") ?? "").trim();
  const numberKeywordFromUrl = (searchParams.get("number") ?? "").trim();
  const initialFilters: TicketFilters = {
    ...emptyTicketFilters,
    playerQuery: playerIdFromUrl,
    drawNo: drawNoFromUrl,
    numberKeyword: numberKeywordFromUrl,
  };
  const [draft, setDraft] = useState<TicketFilters>(initialFilters);
  const [applied, setApplied] = useState<TicketFilters>(initialFilters);
  const [data, setData] = useState<AdminTicketItemsData | null>(null);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(10);

  const load = useCallback(async () => {
    setLoading(true);
    setErr(null);
    try {
      const playerQuery = applied.playerQuery.trim();
      const playerId = Number(playerQuery);
      const query =
        playerQuery === ""
          ? {}
          : Number.isInteger(playerId) && playerId > 0 && String(playerId) === playerQuery
            ? { player_id: playerId }
            : { player_account: playerQuery };

      const d = await getAdminTicketItems({
        page,
        per_page: perPage,
        ...query,
        draw_no: applied.drawNo.trim() || undefined,
        status: applied.statuses.length > 0 ? applied.statuses : undefined,
        number: applied.numberKeyword.trim() || undefined,
        start_date: applied.startDate || undefined,
        end_date: applied.endDate || undefined,
      });
      setData(d);
    } catch (e) {
      setErr(e instanceof LotteryApiBizError ? e.message : tRef.current("loadFailed"));
      setData(null);
    } finally {
      setLoading(false);
    }
  }, [applied, page, perPage, tRef]);

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

  const runSearch = () => {
    setErr(null);
    setApplied({
      ...draft,
      playerQuery: draft.playerQuery.trim(),
      drawNo: draft.drawNo.trim(),
      numberKeyword: draft.numberKeyword.trim(),
    });
    setPage(1);
  };

  const resetFilters = () => {
    setDraft(emptyTicketFilters);
    setApplied(emptyTicketFilters);
    setErr(null);
    setPage(1);
  };

  const toggleStatus = (status: string, checked: boolean) => {
    setDraft((current) => ({
      ...current,
      statuses: checked
        ? [...current.statuses, status]
        : current.statuses.filter((item) => item !== status),
    }));
  };

  return (
    <Card className="admin-list-card w-full max-w-none">
      <CardHeader className="admin-list-header">
        <CardTitle className="admin-list-title">{t("playerTicketQuery")}</CardTitle>
      </CardHeader>
      <CardContent className="admin-list-content">
        <div className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            <TicketFilterField id="pt-player" label={t("playerId")}>
              <Input
                id="pt-player"
                className="h-8 w-full font-mono"
                placeholder={t("playerIdPlaceholder")}
                value={draft.playerQuery}
                onChange={(e) =>
                  setDraft((current) => ({ ...current, playerQuery: e.target.value }))
                }
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    runSearch();
                  }
                }}
              />
            </TicketFilterField>
            <TicketFilterField id="pt-draw" label={t("drawNoOptional")}>
              <Input
                id="pt-draw"
                className="h-8 w-full font-mono"
                placeholder={t("drawNoPlaceholder")}
                value={draft.drawNo}
                onChange={(e) => setDraft((current) => ({ ...current, drawNo: e.target.value }))}
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    runSearch();
                  }
                }}
              />
            </TicketFilterField>
            <TicketFilterField id="pt-number" label={t("numberKeyword")}>
              <Input
                id="pt-number"
                className="h-8 w-full font-mono"
                placeholder={t("numberKeywordPlaceholder")}
                value={draft.numberKeyword}
                onChange={(e) =>
                  setDraft((current) => ({ ...current, numberKeyword: e.target.value }))
                }
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    runSearch();
                  }
                }}
              />
            </TicketFilterField>
            <TicketFilterField id="pt-date-range" label={t("placedDateRange")}>
              <AdminDateRangeField
                id="pt-date-range"
                from={draft.startDate}
                to={draft.endDate}
                onRangeChange={(range) =>
                  setDraft((current) => ({
                    ...current,
                    startDate: range.from,
                    endDate: range.to,
                  }))
                }
              />
            </TicketFilterField>
          </div>

          <div className="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-end sm:justify-between">
            <TicketFilterField id="pt-status" label={t("statusFilterLabel")}>
              <DropdownMenu>
                <DropdownMenuTrigger
                  id="pt-status"
                  title={t("statusHint")}
                  className="inline-flex h-8 w-full min-w-0 items-center justify-between rounded-md border border-border bg-card px-3 text-left text-sm font-normal shadow-sm outline-none transition-all hover:bg-accent focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 sm:min-w-[12rem] sm:max-w-xs"
                >
                  <span className="truncate">{ticketStatusSummary(draft.statuses, t)}</span>
                  <ChevronDown className="size-4 shrink-0 opacity-60" />
                </DropdownMenuTrigger>
                <DropdownMenuContent align="start" className="w-56">
                  {TICKET_STATUS_OPTIONS.map((status) => (
                    <DropdownMenuCheckboxItem
                      key={status}
                      checked={draft.statuses.includes(status)}
                      onCheckedChange={(checked) => toggleStatus(status, checked === true)}
                    >
                      {ticketStatusText(status, t)}
                    </DropdownMenuCheckboxItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>
            </TicketFilterField>
            <div className="admin-list-actions w-full sm:ml-auto sm:w-auto">
              <AdminTableExportButton
                tableId="tickets-table"
                filename={exportLabels.filename}
                sheetName={exportLabels.sheetName}
              />
              <Button type="button" size="sm" onClick={() => runSearch()}>
                {t("query")}
              </Button>
              <Button type="button" size="sm" variant="outline" onClick={() => resetFilters()}>
                {t("resetFilters")}
              </Button>
              <Button type="button" size="sm" variant="secondary" onClick={() => void load()}>
                {t("refreshCurrentPage")}
              </Button>
            </div>
          </div>
        </div>

        {applied.playerQuery || applied.drawNo || applied.numberKeyword || applied.startDate || applied.endDate || applied.statuses.length > 0 ? (
          <p className="text-muted-foreground text-sm">
            {applied.playerQuery ? (
              <>
                {t("playerId")}：<span className="font-mono">{applied.playerQuery}</span>
              </>
            ) : (
              <span>{t("allTickets")}</span>
            )}
            {applied.drawNo ? (
              <>
                {" · "}
                {t("drawNo")}：<span className="font-mono">{applied.drawNo}</span>
              </>
            ) : null}
          </p>
        ) : null}

        {err ? <p className="text-sm text-destructive">{err}</p> : null}
        {loading || data ? (
          <>
            <div className="admin-table-shell">
              <Table id="tickets-table">
                <TableHeader>
                  <TableRow>
                    <TableHead>{t("ticketNo")}</TableHead>
                    <AdminAgentIdentityHeads />
                    <AdminPlayerIdentityHeads />
                    <TableHead>{t("fundingMode", { ns: "players" })}</TableHead>
                    <TableHead>{t("orderNo")}</TableHead>
                    <TableHead>{t("drawNo")}</TableHead>
                    <TableHead>{t("playCode")}</TableHead>
                    <TableHead>{t("number")}</TableHead>
                    <TableHead className="text-center">{t("betAmount")}</TableHead>
                    <TableHead className="text-center">{t("actualDeduct")}</TableHead>
                    <TableHead>{t("status")}</TableHead>
                    <TableHead>{t("failReason")}</TableHead>
                    <TableHead className="text-center">{t("winAmount")}</TableHead>
                    <TableHead>{t("placedAt")}</TableHead>
                    <TableHead>{t("updatedAt")}</TableHead>
                    <TableHead className="sticky right-0 z-20 bg-muted w-12 text-center shadow-[-1px_0_0_rgba(203,213,225,0.7)]">{t("table.actions", { ns: "common" })}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading && !data ? (
                    <AdminTableLoadingRow colSpan={18} />
                  ) : !data || data.items.length === 0 ? (
                    <AdminTableNoResourceRow colSpan={18} />
                  ) : (
                    data.items.map((row) => {
                      const winLabel = row.jackpot_win_amount > 0
                        ? `${row.win_amount_formatted} + ${row.jackpot_win_amount_formatted}`
                        : row.win_amount_formatted;
                      return (
                        <TableRow key={row.ticket_no}>
                          <TableCell className="font-mono text-xs">
                            <Link
                              href={ticketDetailPath(row.ticket_no)}
                              className="text-primary hover:underline"
                            >
                              {row.ticket_no}
                            </Link>
                          </TableCell>
                          <AdminAgentIdentityCells row={row} />
                          <AdminPlayerIdentityCells row={row} />
                          <TableCell className="text-xs">
                            <PlayerFundingModeBadge row={row} />
                          </TableCell>
                          <TableCell className="font-mono text-xs">{row.order_no ?? "—"}</TableCell>
                          <TableCell className="font-mono text-xs">{row.draw_no ?? "—"}</TableCell>
                          <TableCell className="text-xs">{playCodeLabel(row.play_code)}</TableCell>
                          <TableCell className="font-mono text-xs">{row.original_number ?? "—"}</TableCell>
                          <TableCell className="text-center tabular-nums text-xs">
                            {row.total_bet_amount_formatted}
                          </TableCell>
                          <TableCell className="text-center tabular-nums text-xs">
                            {row.actual_deduct_amount_formatted}
                          </TableCell>
                          <TableCell className="text-xs">
                            <AdminStatusBadge status={row.status}>
                              {ticketStatusText(row.status, t)}
                            </AdminStatusBadge>
                          </TableCell>
                          <TableCell className="max-w-[14rem] text-xs text-muted-foreground">
                            {row.fail_reason_text ?? row.fail_reason_code ?? "—"}
                          </TableCell>
                          <TableCell className="text-center tabular-nums text-xs">{winLabel}</TableCell>
                          <TableCell className="text-xs">{formatTs(row.placed_at)}</TableCell>
                          <TableCell className="text-xs">{formatTs(row.updated_at)}</TableCell>
                          <TableCell className="sticky right-0 z-10 bg-card text-center shadow-[-1px_0_0_rgba(203,213,225,0.7)]">
                            <AdminRowActionsMenu
                              actions={
                                row.player_id
                                  ? [
                                      {
                                        key: "view-player",
                                        label: t("viewPlayer"),
                                        icon: Eye,
                                        href: adminPlayerDetailPath(row.player_id),
                                      },
                                    ]
                                  : []
                              }
                            />
                          </TableCell>
                        </TableRow>
                      );
                    })
                  )}
                </TableBody>
              </Table>
            </div>
            {data ? (
              <AdminListPaginationFooter
                selectId="player-tickets-per-page"
                total={data.total}
                page={data.page}
                lastPage={Math.max(1, data.last_page)}
                perPage={data.per_page}
                loading={loading}
                onPerPageChange={(n) => {
                  setPerPage(n);
                  setPage(1);
                }}
                onPageChange={setPage}
              />
            ) : null}
          </>
        ) : null}
      </CardContent>
    </Card>
  );
}
