"use client";

import { useCallback, useState } from "react";
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 { getAdminAuditLogs } from "@/api/admin-audit";
import { AdminDateRangeField } from "@/components/admin/admin-date-range-field";
import { AdminNoResourceState, AdminTableNoResourceRow } from "@/components/admin/admin-no-resource-state";
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 { AdminTableLoadingRow } from "@/components/admin/admin-loading-state";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
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";

const MODULE_FILTER_OPTIONS = [
  "agent",
  "system",
  "settings",
  "integration",
  "player_manage",
  "player_service",
  "draw",
  "settlement",
  "wallet",
  "reconcile",
  "reconcile_jobs",
  "report_jobs",
  "odds",
  "play_config",
  "risk_cap",
  "jackpot",
  "dashboard",
] as const;

const OPERATOR_TYPE_OPTIONS = ["admin", "player", "system"] as const;

export function AuditLogsConsole(): React.ReactElement {
  const { t } = useTranslation(["audit", "common"]);
  const tRef = useTranslationRef(["audit", "common"]);
  const exportLabels = useExportLabels("auditLogs");
  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(10);
  const [operatorId, setOperatorId] = useState("");
  const [moduleCode, setModuleCode] = useState("all");
  const [operatorType, setOperatorType] = useState("all");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [appliedOperatorId, setAppliedOperatorId] = useState("");
  const [appliedModule, setAppliedModule] = useState("all");
  const [appliedOpType, setAppliedOpType] = useState("all");
  const [appliedStartDate, setAppliedStartDate] = useState("");
  const [appliedEndDate, setAppliedEndDate] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    setErr(null);
    try {
      const operatorIdValue = appliedOperatorId.trim();
      const parsedOperatorId = Number(operatorIdValue);
      const operatorIdParam =
        operatorIdValue !== "" && Number.isInteger(parsedOperatorId) && parsedOperatorId > 0
          ? parsedOperatorId
          : undefined;

      const d = await getAdminAuditLogs({
        page,
        per_page: perPage,
        operator_id: operatorIdParam,
        module_code: appliedModule !== "all" ? appliedModule : undefined,
        operator_type: appliedOpType !== "all" ? appliedOpType : undefined,
        start_date: appliedStartDate || undefined,
        end_date: appliedEndDate || undefined,
      });
      setData(d);
    } catch (e) {
      setErr(e instanceof LotteryApiBizError ? e.message : tRef.current("errors.loadFailed", { ns: "common" }));
      setData(null);
    } finally {
      setLoading(false);
    }
  }, [page, perPage, appliedOperatorId, appliedModule, appliedOpType, appliedStartDate, appliedEndDate, tRef]);

  useAsyncEffect(() => {
    void load();
  }, [page, perPage, appliedOperatorId, appliedModule, appliedOpType, appliedStartDate, appliedEndDate]);

  const meta = data?.meta;

  const operatorTypeLabel = (type: string): string => {
    const key = `operatorTypes.${type}` as const;
    const translated = t(key);
    return translated === key ? type : translated;
  };

  const showTargetColumn = (row: AdminAuditLogListData["items"][number]): boolean => {
    const summary = row.summary_label || `${row.module_label} · ${row.action_label}`;
    const target = row.target_label;
    if (!target || target === "—") {
      return false;
    }
    return !summary.includes(target);
  };

  return (
    <Card className="admin-list-card w-full max-w-none">
        <CardHeader className="admin-list-header">
          <CardTitle className="admin-list-title">{t("title")}</CardTitle>
        </CardHeader>
        <CardContent className="admin-list-content">
          <div className="admin-list-toolbar">
            <div className="admin-list-field">
              <Label htmlFor="aud-module" className="sm:shrink-0">
                {t("filterModule")}
              </Label>
              <Select value={moduleCode} onValueChange={(value) => setModuleCode(value ?? "all")}>
                <SelectTrigger id="aud-module" className="w-full sm:w-44">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">{t("filterModuleAll")}</SelectItem>
                  {MODULE_FILTER_OPTIONS.map((code) => (
                    <SelectItem key={code} value={code}>
                      {t(`moduleOptions.${code}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="admin-list-field">
              <Label htmlFor="aud-op-type" className="sm:shrink-0">
                {t("filterOperatorType")}
              </Label>
              <Select value={operatorType} onValueChange={(value) => setOperatorType(value ?? "all")}>
                <SelectTrigger id="aud-op-type" className="w-full sm:w-36">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">{t("filterOperatorTypeAll")}</SelectItem>
                  {OPERATOR_TYPE_OPTIONS.map((code) => (
                    <SelectItem key={code} value={code}>
                      {t(`operatorTypes.${code}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="admin-list-field">
              <Label htmlFor="aud-operator-id" className="sm:shrink-0">
                {t("operator")}
              </Label>
              <Input
                id="aud-operator-id"
                value={operatorId}
                onChange={(e) => setOperatorId(e.target.value)}
                placeholder={t("operatorIdPlaceholder")}
                className="w-full sm:w-36"
                inputMode="numeric"
              />
            </div>
            <div className="admin-list-field">
              <Label htmlFor="aud-date-range" className="sm:shrink-0">
                {t("time")}
              </Label>
              <div className="min-w-0 w-full sm:w-56">
                <AdminDateRangeField
                  id="aud-date-range"
                  from={startDate}
                  to={endDate}
                  onRangeChange={(range) => {
                    setStartDate(range.from);
                    setEndDate(range.to);
                  }}
                />
              </div>
            </div>
            <div className="admin-list-actions">
              <AdminTableExportButton
                tableId="audit-logs-table"
                filename={exportLabels.filename}
                sheetName={exportLabels.sheetName}
              />
              <Button
                type="button"
                onClick={() => {
                  setAppliedOperatorId(operatorId);
                  setAppliedModule(moduleCode);
                  setAppliedOpType(operatorType);
                  setAppliedStartDate(startDate);
                  setAppliedEndDate(endDate);
                  setPage(1);
                }}
              >
                {t("actions.search", { ns: "common" })}
              </Button>
              <Button
                type="button"
                variant="secondary"
                onClick={() => {
                  setOperatorId("");
                  setModuleCode("all");
                  setOperatorType("all");
                  setStartDate("");
                  setEndDate("");
                  setAppliedOperatorId("");
                  setAppliedModule("all");
                  setAppliedOpType("all");
                  setAppliedStartDate("");
                  setAppliedEndDate("");
                  setPage(1);
                }}
              >
                {t("actions.reset", { ns: "common" })}
              </Button>
            </div>
          </div>
          {err ? <p className="text-sm text-destructive">{err}</p> : null}
          {(loading && !data) || data ? (
            <>
              <div className="admin-table-shell">
                <Table id="audit-logs-table">
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-40 whitespace-nowrap">{t("time")}</TableHead>
                      <TableHead className="w-36">{t("operator")}</TableHead>
                      <TableHead>{t("summary")}</TableHead>
                      <TableHead className="w-36">{t("target")}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading && !data ? (
                      <AdminTableLoadingRow colSpan={4} />
                    ) : !data || data.items.length === 0 ? (
                      <AdminTableNoResourceRow colSpan={4} message={t("empty")} />
                    ) : (
                      data.items.map((row) => (
                        <TableRow key={row.id}>
                          <TableCell className="whitespace-nowrap text-sm text-muted-foreground">
                            {formatTs(row.created_at)}
                          </TableCell>
                          <TableCell className="text-sm">
                            <div className="font-medium text-foreground">{row.operator_label}</div>
                            <div className="text-xs text-muted-foreground">
                              {operatorTypeLabel(row.operator_type)}
                            </div>
                          </TableCell>
                          <TableCell className="text-sm leading-relaxed">
                            {row.summary_label || `${row.module_label} · ${row.action_label}`}
                          </TableCell>
                          <TableCell className="text-sm text-muted-foreground">
                            {showTargetColumn(row) ? row.target_label : "—"}
                          </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}
            </>
          ) : (
            <AdminNoResourceState message={t("empty")} />
          )}
        </CardContent>
      </Card>
  );
}