"use client";

import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { getAdminAuditLogs } from "@/api/admin-audit";
import { AdminListPaginationFooter } from "@/components/admin/admin-list-pagination-footer";
import { AdminTableExportButton } from "@/components/admin/admin-table-export-button";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminAuditLogListData } from "@/types/api/admin-audit";

export function AuditLogsConsole(): React.ReactElement {
  const { t } = useTranslation(["audit", "common"]);
  const formatTs = useAdminDateTimeFormatter();
  const [data, setData] = useState<AdminAuditLogListData | null>(null);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(25);
  const [moduleCode, setModuleCode] = useState("");
  const [actionCode, setActionCode] = useState("");
  const [operatorType, setOperatorType] = useState("");
  const [appliedModule, setAppliedModule] = useState("");
  const [appliedAction, setAppliedAction] = useState("");
  const [appliedOpType, setAppliedOpType] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    setErr(null);
    try {
      const d = await getAdminAuditLogs({
        page,
        per_page: perPage,
        module_code: appliedModule.trim() || undefined,
        action_code: appliedAction.trim() || undefined,
        operator_type: appliedOpType.trim() || undefined,
      });
      setData(d);
    } catch (e) {
      setErr(e instanceof LotteryApiBizError ? e.message : t("errors.loadFailed", { ns: "common" }));
      setData(null);
    } finally {
      setLoading(false);
    }
  }, [page, perPage, appliedModule, appliedAction, appliedOpType, t]);

  useEffect(() => {
    queueMicrotask(() => {
      void load();
    });
  }, [load]);

  const meta = data?.meta;

  return (
    <Card className="admin-list-card w-full max-w-none">
      <CardHeader className="admin-list-header flex flex-col gap-5">
        <CardTitle className="admin-list-title">{t("title")}</CardTitle>
        <div className="grid gap-3 lg:grid-cols-3">
          <div className="flex min-w-0 items-center gap-2">
            <Label htmlFor="aud-mod" className="shrink-0 whitespace-nowrap">
              {t("moduleCode")}
            </Label>
            <Input
              id="aud-mod"
              value={moduleCode}
              onChange={(e) => setModuleCode(e.target.value)}
              placeholder={t("exactMatch")}
              className="w-full"
            />
          </div>
          <div className="flex min-w-0 items-center gap-2">
            <Label htmlFor="aud-act" className="shrink-0 whitespace-nowrap">
              {t("actionCode")}
            </Label>
            <Input
              id="aud-act"
              value={actionCode}
              onChange={(e) => setActionCode(e.target.value)}
              placeholder={t("exactMatch")}
              className="w-full"
            />
          </div>
          <div className="flex min-w-0 items-center gap-2">
            <Label htmlFor="aud-op" className="shrink-0 whitespace-nowrap">
              {t("operatorType")}
            </Label>
            <Input
              id="aud-op"
              value={operatorType}
              onChange={(e) => setOperatorType(e.target.value)}
              placeholder={t("operatorTypePlaceholder")}
              className="w-full"
            />
          </div>
        </div>
        <div className="flex flex-wrap justify-end gap-2">
          <AdminTableExportButton
            tableId="audit-logs-table"
            filename="审计日志"
            sheetName="审计日志"
          />
          <Button
            type="button"
            onClick={() => {
              setAppliedModule(moduleCode);
              setAppliedAction(actionCode);
              setAppliedOpType(operatorType);
              setPage(1);
            }}
          >
            {t("actions.search", { ns: "common" })}
          </Button>
          <Button
            type="button"
            variant="secondary"
            onClick={() => {
              setModuleCode("");
              setActionCode("");
              setOperatorType("");
              setAppliedModule("");
              setAppliedAction("");
              setAppliedOpType("");
              setPage(1);
            }}
          >
            {t("actions.reset", { ns: "common", defaultValue: "重置" })}
          </Button>
        </div>
      </CardHeader>
      <CardContent className="admin-list-content">
        {err ? <p className="text-sm text-red-600 dark:text-red-400">{err}</p> : null}
        {loading && !data ? (
          <p className="text-muted-foreground text-sm">{t("states.loading", { ns: "common" })}</p>
        ) : null}

        {data ? (
          <>
            <div className="rounded-md border">
              <Table id="audit-logs-table">
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-20">{t("table.id", { ns: "common" })}</TableHead>
                    <TableHead>{t("operator")}</TableHead>
                    <TableHead>{t("module")}</TableHead>
                    <TableHead>{t("action")}</TableHead>
                    <TableHead>{t("target")}</TableHead>
                    <TableHead>{t("time")}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {data.items.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={6} className="text-muted-foreground">
                        {t("empty")}
                      </TableCell>
                    </TableRow>
                  ) : (
                    data.items.map((row) => (
                      <TableRow key={row.id}>
                        <TableCell>{row.id}</TableCell>
                        <TableCell className="text-xs">
                          {row.operator_type}:{row.operator_id}
                        </TableCell>
                        <TableCell className="font-mono text-xs">{row.module_code}</TableCell>
                        <TableCell className="font-mono text-xs">{row.action_code}</TableCell>
                        <TableCell className="text-xs text-muted-foreground">
                          {row.target_type ?? "—"} {row.target_id ?? ""}
                        </TableCell>
                        <TableCell className="whitespace-nowrap font-mono text-[11px] text-muted-foreground">
                          {formatTs(row.created_at)}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
            {meta ? (
              <AdminListPaginationFooter
                selectId="audit-logs-per-page"
                total={meta.total}
                page={meta.current_page}
                lastPage={Math.max(1, meta.last_page)}
                perPage={meta.per_page}
                loading={loading}
                onPerPageChange={(n) => {
                  setPerPage(n);
                  setPage(1);
                }}
                onPageChange={setPage}
              />
            ) : null}
          </>
        ) : null}
      </CardContent>
    </Card>
  );
}
