"use client";

import type React from "react";
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 { getAdminJackpotContributions, getAdminJackpotPayoutLogs } from "@/api/admin-jackpot";
import { AdminListPaginationFooter } from "@/components/admin/admin-list-pagination-footer";
import { AdminTableNoResourceRow } from "@/components/admin/admin-no-resource-state";
import { AdminPlayerIdentityCells, AdminPlayerIdentityHeads } from "@/components/admin/admin-player-identity-columns";
import { AdminTableExportButton } from "@/components/admin/admin-table-export-button";
import { AdminSubnav, AdminSubnavButton } from "@/components/admin/admin-subnav";
import { ModuleScaffold } from "@/components/admin/module-scaffold";
import { Button } from "@/components/ui/button";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { AdminLoadingState } 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 { useExportLabels } from "@/hooks/use-export-labels";
import { formatAdminMinorUnits } from "@/lib/money";
import { LotteryApiBizError } from "@/types/api/errors";
import type {
  AdminJackpotContributionsData,
  AdminJackpotPayoutLogsData,
} from "@/types/api/admin-jackpot";

type JackpotRecordsConsoleProps = {
  embedded?: boolean;
};

/** 表格在 admin-table-shell 内时去掉 Table 组件自带的第二层边框 */
const TABLE_IN_SHELL_CLASS =
  "[&_[data-slot=table-container]]:rounded-none [&_[data-slot=table-container]]:border-0 [&_[data-slot=table-container]]:bg-transparent [&_[data-slot=table-container]]:shadow-none";

/** 流水表左对齐文本列，避免 table-fixed 拉宽空白列 */
const TABLE_LAYOUT_CLASS =
  "w-full min-w-[42rem] text-left [&_[data-slot=table-head]]:text-left [&_[data-slot=table-cell]]:text-left";

function JackpotRecordTableSection({
  title,
  tableId,
  exportFilename,
  exportSheetName,
  loading,
  hasData,
  children,
  footer,
}: {
  title: string;
  tableId: string;
  exportFilename: string;
  exportSheetName: string;
  loading: boolean;
  hasData: boolean;
  children: React.ReactNode;
  footer: React.ReactNode;
}) {
  return (
    <div className="admin-table-shell">
      <div className="flex flex-wrap items-center justify-between gap-2 border-b border-border/70 bg-muted/20 px-4 py-3">
        <h3 className="text-sm font-semibold text-foreground">{title}</h3>
        <AdminTableExportButton
          tableId={tableId}
          filename={exportFilename}
          sheetName={exportSheetName}
        />
      </div>
      {loading && !hasData ? (
        <AdminLoadingState minHeight="6rem" className="px-4 py-6" />
      ) : (
        <div className={TABLE_IN_SHELL_CLASS}>{children}</div>
      )}
      {footer ? <div className="px-4 pb-4">{footer}</div> : null}
    </div>
  );
}

type RecordTab = "payout" | "contribution";

export function JackpotRecordsConsole({ embedded = false }: JackpotRecordsConsoleProps) {
  const { t } = useTranslation(["jackpot", "common"]);
  const tRef = useTranslationRef(["jackpot"]);
  const [recordTab, setRecordTab] = useState<RecordTab>("payout");
  const payoutExport = useExportLabels("jackpotPayouts");
  const contributionExport = useExportLabels("jackpotContributions");
  const formatDt = useAdminDateTimeFormatter();
  const [drawNo, setDrawNo] = useState("");
  const [appliedDrawNo, setAppliedDrawNo] = useState("");

  const [payouts, setPayouts] = useState<AdminJackpotPayoutLogsData | null>(null);
  const [pPage, setPPage] = useState(1);
  const [pPer, setPPer] = useState(10);

  const [contribs, setContribs] = useState<AdminJackpotContributionsData | null>(null);
  const [cPage, setCPage] = useState(1);
  const [cPer, setCPer] = useState(10);

  const [loadingP, setLoadingP] = useState(true);
  const [loadingC, setLoadingC] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  const loadPayouts = useCallback(async () => {
    setLoadingP(true);
    try {
      const d = await getAdminJackpotPayoutLogs({
        page: pPage,
        per_page: pPer,
        draw_no: appliedDrawNo.trim() || undefined,
      });
      setPayouts(d);
    } catch (e) {
      setErr(e instanceof LotteryApiBizError ? e.message : tRef.current("payoutLoadFailed"));
    } finally {
      setLoadingP(false);
    }
  }, [pPage, pPer, appliedDrawNo, tRef]);

  const loadContribs = useCallback(async () => {
    setLoadingC(true);
    try {
      const d = await getAdminJackpotContributions({
        page: cPage,
        per_page: cPer,
        draw_no: appliedDrawNo.trim() || undefined,
      });
      setContribs(d);
    } catch (e) {
      setErr(e instanceof LotteryApiBizError ? e.message : tRef.current("contributionLoadFailed"));
    } finally {
      setLoadingC(false);
    }
  }, [cPage, cPer, appliedDrawNo, tRef]);

  useAsyncEffect(() => {
    void loadPayouts();
  }, [pPage, pPer, appliedDrawNo]);

  useAsyncEffect(() => {
    if (recordTab !== "contribution") {
      return;
    }
    void loadContribs();
  }, [recordTab, cPage, cPer, appliedDrawNo]);

  const applyDraw = () => {
    setAppliedDrawNo(drawNo);
    setPPage(1);
    setCPage(1);
  };

  const triggerTypeText = (value: string) => {
    const key = `triggerTypes.${value}`;
    const translated = t(key);
    return translated === key ? value : translated;
  };

  const filterToolbar = (
    <div className="admin-list-toolbar">
      <div className="admin-list-field">
        <Label htmlFor="jk-draw" className="sm:shrink-0">
          {t("drawNo")}
        </Label>
        <Input
          id="jk-draw"
          className="h-9 w-full font-mono sm:w-[18rem]"
          value={drawNo}
          onChange={(e) => setDrawNo(e.target.value)}
          placeholder={t("optional")}
          onKeyDown={(e) => {
            if (e.key === "Enter") {
              applyDraw();
            }
          }}
        />
      </div>
      <div className="admin-list-actions">
        <Button type="button" size="sm" className="h-9" onClick={applyDraw}>
          {t("apply")}
        </Button>
      </div>
    </div>
  );

  const payoutFooter = payouts ? (
    <AdminListPaginationFooter
      selectId="jk-payout-per"
      total={payouts.meta.total}
      page={payouts.meta.current_page}
      lastPage={payouts.meta.last_page}
      perPage={payouts.meta.per_page}
      loading={loadingP}
      onPerPageChange={(n) => {
        setPPer(n);
        setPPage(1);
      }}
      onPageChange={setPPage}
    />
  ) : null;

  const contributionFooter = contribs ? (
    <AdminListPaginationFooter
      selectId="jk-contrib-per"
      total={contribs.meta.total}
      page={contribs.meta.current_page}
      lastPage={contribs.meta.last_page}
      perPage={contribs.meta.per_page}
      loading={loadingC}
      onPerPageChange={(n) => {
        setCPer(n);
        setCPage(1);
      }}
      onPageChange={setCPage}
    />
  ) : null;

  const payoutTable = (
    <JackpotRecordTableSection
      title={t("payoutRecords")}
      tableId="jackpot-payout-table"
      exportFilename={payoutExport.filename}
      exportSheetName={payoutExport.sheetName}
      loading={loadingP}
      hasData={payouts != null}
      footer={payoutFooter}
    >
      <Table id="jackpot-payout-table" className={TABLE_LAYOUT_CLASS}>
        <TableHeader>
          <TableRow>
            <TableHead className="w-16 whitespace-nowrap">{t("table.id", { ns: "common" })}</TableHead>
            <TableHead className="whitespace-nowrap">{t("drawNo")}</TableHead>
            <TableHead className="whitespace-nowrap">{t("trigger")}</TableHead>
            <TableHead className="whitespace-nowrap text-right">{t("payoutAmount")}</TableHead>
            <TableHead className="w-24 whitespace-nowrap text-right">{t("winnerCount")}</TableHead>
            <TableHead className="whitespace-nowrap">{t("time")}</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {(payouts?.items ?? []).length === 0 ? (
            <AdminTableNoResourceRow colSpan={6} className="py-10 text-center text-muted-foreground" />
          ) : (
            (payouts?.items ?? []).map((r) => (
              <TableRow key={r.id}>
                <TableCell className="font-mono text-xs">{r.id}</TableCell>
                <TableCell className="font-mono text-xs">{r.draw_no ?? "—"}</TableCell>
                <TableCell className="text-xs">{triggerTypeText(r.trigger_type)}</TableCell>
                <TableCell className="text-right text-sm font-semibold">
                  {formatAdminMinorUnits(r.total_payout_amount, r.currency_code ?? "NPR")}
                </TableCell>
                <TableCell className="text-right tabular-nums">{r.winner_count}</TableCell>
                <TableCell className="text-xs text-muted-foreground whitespace-nowrap">
                  {formatDt(r.created_at)}
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
    </JackpotRecordTableSection>
  );

  const contributionTable = (
    <JackpotRecordTableSection
      title={t("contributionRecords")}
      tableId="jackpot-contribution-table"
      exportFilename={contributionExport.filename}
      exportSheetName={contributionExport.sheetName}
      loading={loadingC}
      hasData={contribs != null}
      footer={contributionFooter}
    >
      <Table id="jackpot-contribution-table" className={TABLE_LAYOUT_CLASS}>
        <TableHeader>
          <TableRow>
            <TableHead className="w-16 whitespace-nowrap">{t("table.id", { ns: "common" })}</TableHead>
            <TableHead className="whitespace-nowrap">{t("drawNo")}</TableHead>
            <TableHead className="whitespace-nowrap">{t("ticketNo")}</TableHead>
            <AdminPlayerIdentityHeads />
            <TableHead className="whitespace-nowrap text-right">{t("contributionAmount")}</TableHead>
            <TableHead className="whitespace-nowrap">{t("time")}</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {(contribs?.items ?? []).length === 0 ? (
            <AdminTableNoResourceRow colSpan={8} className="py-10 text-center text-muted-foreground" />
          ) : (
            (contribs?.items ?? []).map((r) => (
              <TableRow key={r.id}>
                <TableCell className="font-mono text-xs">{r.id}</TableCell>
                <TableCell className="font-mono text-xs">{r.draw_no ?? "—"}</TableCell>
                <TableCell className="font-mono text-xs">{r.ticket_no ?? "—"}</TableCell>
                <AdminPlayerIdentityCells row={r} />
                <TableCell className="text-right text-sm font-semibold">
                  {formatAdminMinorUnits(r.contribution_amount, r.currency_code ?? "NPR")}
                </TableCell>
                <TableCell className="text-xs text-muted-foreground whitespace-nowrap">
                  {formatDt(r.created_at)}
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
    </JackpotRecordTableSection>
  );

  const content = (
    <>
      <div className="space-y-3">
        <AdminSubnav aria-label={t("pageTabs")}>
          <AdminSubnavButton
            active={recordTab === "payout"}
            onClick={() => setRecordTab("payout")}
          >
            {t("payoutRecords")}
          </AdminSubnavButton>
          <AdminSubnavButton
            active={recordTab === "contribution"}
            onClick={() => setRecordTab("contribution")}
          >
            {t("contributionRecords")}
          </AdminSubnavButton>
        </AdminSubnav>
        {filterToolbar}
      </div>

      {err ? <p className="text-destructive text-sm">{err}</p> : null}

      <div className="space-y-6">
        {recordTab === "payout" ? payoutTable : contributionTable}
      </div>
    </>
  );

  if (embedded) {
    return content;
  }

  return <ModuleScaffold>{content}</ModuleScaffold>;
}
