"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 { AdminLoadingState, AdminLoadingInline, 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 { LotteryApiBizError } from "@/types/api/errors";
import type { AdminAuditLogListData } from "@/types/api/admin-audit";

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("");
  const [actionCode, setActionCode] = useState("");
  const [operatorType, setOperatorType] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [appliedOperatorId, setAppliedOperatorId] = useState("");
  const [appliedModule, setAppliedModule] = useState("");
  const [appliedAction, setAppliedAction] = useState("");
  const [appliedOpType, setAppliedOpType] = useState("");
  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.trim() || undefined,
        action_code: appliedAction.trim() || undefined,
        operator_type: appliedOpType.trim() || 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, appliedAction, appliedOpType, appliedStartDate, appliedEndDate]);

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

  const meta = data?.meta;

  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-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-mod" className="sm:shrink-0">
              {t("moduleCode")}
            </Label>
            <Input
              id="aud-mod"
              value={moduleCode}
              onChange={(e) => setModuleCode(e.target.value)}
              placeholder={t("exactMatch")}
              className="w-full sm:w-40"
            />
          </div>
          <div className="admin-list-field">
            <Label htmlFor="aud-act" className="sm:shrink-0">
              {t("actionCode")}
            </Label>
            <Input
              id="aud-act"
              value={actionCode}
              onChange={(e) => setActionCode(e.target.value)}
              placeholder={t("exactMatch")}
              className="w-full sm:w-40"
            />
          </div>
          <div className="admin-list-field">
            <Label htmlFor="aud-op" className="sm:shrink-0">
              {t("operatorType")}
            </Label>
            <Input
              id="aud-op"
              value={operatorType}
              onChange={(e) => setOperatorType(e.target.value)}
              placeholder={t("operatorTypePlaceholder")}
              className="w-full sm:w-40"
            />
          </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);
                setAppliedAction(actionCode);
                setAppliedOpType(operatorType);
                setAppliedStartDate(startDate);
                setAppliedEndDate(endDate);
                setPage(1);
              }}
            >
              {t("actions.search", { ns: "common" })}
            </Button>
            <Button
              type="button"
              variant="secondary"
              onClick={() => {
                setOperatorId("");
                setModuleCode("");
                setActionCode("");
                setOperatorType("");
                setStartDate("");
                setEndDate("");
                setAppliedOperatorId("");
                setAppliedModule("");
                setAppliedAction("");
                setAppliedOpType("");
                setAppliedStartDate("");
                setAppliedEndDate("");
                setPage(1);
              }}
            >
              {t("actions.reset", { ns: "common" })}
            </Button>
          </div>
        </div>
        {err ? <p className="text-sm text-red-600 dark:text-red-400">{err}</p> : null}
        {(loading && !data) || data ? (
          <>
            <div className="admin-table-shell">
              <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>
                  {loading && !data ? (
                    <AdminTableLoadingRow colSpan={6} />
                  ) : !data || data.items.length === 0 ? (
                    <AdminTableNoResourceRow colSpan={6} />
                  ) : (
                    data.items.map((row) => (
                      <TableRow key={row.id}>
                        <TableCell>{row.id}</TableCell>
                        <TableCell className="text-xs">
                          <div className="font-medium text-foreground">{row.operator_label}</div>
                          {row.operator_subtitle ? (
                            <div className="text-muted-foreground">{row.operator_subtitle}</div>
                          ) : null}
                        </TableCell>
                        <TableCell className="text-sm">{row.module_label}</TableCell>
                        <TableCell className="text-sm">{row.action_label}</TableCell>
                        <TableCell className="text-sm text-muted-foreground">{row.target_label}</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>
  );
}
