"use client";

import { type ReactNode, useState, useEffect } from "react";
import {
  useAuditLogs,
  useAuditLogFilter,
  exportAuditLogsCsv,
} from "@/hooks/use-audit-logs";
import { useToast } from "@/providers/toast-provider";
import { AuditLogsTabs } from "@/components/audit-logs-tabs";
import {
  PageHeader,
  PaperCard,
  Input,
  Select,
  Button,
  LoadingState,
  ErrorState,
  EmptyState,
  Table,
  TableRow,
  TableCell,
  Pagination,
} from "@/components/ui";
import { t } from "@/lib/i18n";

export default function AuditLogsPage(): ReactNode {
  const { filter, setPage, setSearch, setAction } = useAuditLogFilter();
  const { data, loading, error } = useAuditLogs(filter);
  const { show } = useToast();
  const [searchInput, setSearchInput] = useState("");

  useEffect(() => {
    const timer = setTimeout(() => setSearch(searchInput), 300);
    return () => clearTimeout(timer);
  }, [searchInput, setSearch]);

  const handleExport = () => {
    if (!data || data.items.length === 0) {
      show("warning", "暂无数据可导出");
      return;
    }
    exportAuditLogsCsv(data.items);
    show("success", "已导出 CSV");
  };

  return (
    <div style={{ padding: 32, maxWidth: 1200, margin: "0 auto" }}>
      <PageHeader
        title={t("admin.auditLogs.title")}
        description="系统所有操作的审计记录"
        actions={
          <Button variant="secondary" onClick={handleExport}>
            {t("admin.auditLogs.exportCsv")}
          </Button>
        }
      />

      <AuditLogsTabs />

      <PaperCard className="p-4 mb-4">
        <div className="flex gap-3 items-center">
          <Input
            type="search"
            placeholder={t("admin.common.search")}
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            style={{ width: 240 }}
          />
          <Select
            value={filter.action ?? ""}
            onChange={(e) => setAction(e.target.value)}
          >
            <option value="">{t("admin.common.all")}操作</option>
            <option value="USER_LOGIN">用户登录</option>
            <option value="USER_CREATE">创建用户</option>
            <option value="USER_UPDATE">更新用户</option>
            <option value="USER_TOGGLE_STATUS">切换状态</option>
            <option value="ROLE_CREATE">创建角色</option>
            <option value="ROLE_UPDATE">更新角色</option>
            <option value="VIEWPORT_UPDATE">更新视口</option>
            <option value="SYSTEM_SETTINGS_UPDATE">系统设置</option>
            <option value="ABNORMAL_LOGIN_BLOCKED">异常登录拦截</option>
          </Select>
        </div>
      </PaperCard>

      <PaperCard className="p-4">
        {loading && <LoadingState />}
        {error && <ErrorState message={error.message} />}
        {!loading && !error && data && (
          <>
            {data.items.length === 0 ? (
              <EmptyState message={t("admin.common.empty")} />
            ) : (
              <>
                <Table
                  headers={[
                    t("admin.auditLogs.time"),
                    t("admin.auditLogs.actor"),
                    t("admin.auditLogs.action"),
                    t("admin.auditLogs.resource"),
                    t("admin.auditLogs.resourceId"),
                    t("admin.auditLogs.ip"),
                    t("admin.auditLogs.traceId"),
                  ]}
                >
                  {data.items.map((log) => (
                    <TableRow key={log.id}>
                      <TableCell style={{ whiteSpace: "nowrap" }}>
                        {new Date(log.occurredAt).toLocaleString("zh-CN")}
                      </TableCell>
                      <TableCell>{log.actorName}</TableCell>
                      <TableCell>
                        <span
                          style={{
                            fontFamily: "var(--font-mono)",
                            fontSize: 11,
                          }}
                        >
                          {log.action}
                        </span>
                      </TableCell>
                      <TableCell>{log.resourceType}</TableCell>
                      <TableCell
                        style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}
                      >
                        {log.resourceId}
                      </TableCell>
                      <TableCell
                        style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}
                      >
                        {log.ip}
                      </TableCell>
                      <TableCell
                        style={{
                          fontFamily: "var(--font-mono)",
                          fontSize: 11,
                          color: "var(--color-ink-muted)",
                        }}
                      >
                        {log.traceId ?? "—"}
                      </TableCell>
                    </TableRow>
                  ))}
                </Table>
                <Pagination
                  page={data.page}
                  pageSize={data.pageSize}
                  total={data.total}
                  hasNext={data.hasNext}
                  onPageChange={setPage}
                />
              </>
            )}
          </>
        )}
      </PaperCard>
    </div>
  );
}
