"use client";

import { type ReactNode, useState, useEffect } from "react";
import {
  useDataChangeLogs,
  useDataChangeLogFilter,
  exportDataChangeLogsCsv,
} from "@/hooks/use-data-change-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 DataChangesPage(): ReactNode {
  const { filter, setPage, setSearch, setTableName, setAction } =
    useDataChangeLogFilter();
  const { data, loading, error } = useDataChangeLogs(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;
    }
    exportDataChangeLogsCsv(data.items);
    show("success", "已导出 CSV");
  };

  return (
    <div style={{ padding: 32, maxWidth: 1200, margin: "0 auto" }}>
      <PageHeader
        title={t("admin.auditLogs.dataChanges")}
        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.tableName ?? ""}
            onChange={(e) => setTableName(e.target.value)}
          >
            <option value="">{t("admin.common.all")}数据表</option>
            <option value="users">用户表</option>
            <option value="roles">角色表</option>
            <option value="viewports">视口表</option>
            <option value="system_settings">系统设置表</option>
          </Select>
          <Select
            value={filter.action ?? ""}
            onChange={(e) => setAction(e.target.value)}
          >
            <option value="">{t("admin.common.all")}操作</option>
            <option value="create">创建</option>
            <option value="update">更新</option>
            <option value="delete">删除</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.tableName"),
                    t("admin.auditLogs.action"),
                    t("admin.auditLogs.recordId"),
                    t("admin.auditLogs.beforeState"),
                    t("admin.auditLogs.afterState"),
                    t("admin.auditLogs.ip"),
                  ]}
                >
                  {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
                        style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}
                      >
                        {log.tableName}
                      </TableCell>
                      <TableCell>
                        <span
                          style={{
                            fontFamily: "var(--font-mono)",
                            fontSize: 11,
                          }}
                        >
                          {log.action}
                        </span>
                      </TableCell>
                      <TableCell
                        style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}
                      >
                        {log.recordId}
                      </TableCell>
                      <TableCell
                        style={{
                          fontFamily: "var(--font-mono)",
                          fontSize: 11,
                          maxWidth: 200,
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap",
                        }}
                      >
                        {log.beforeState ?? "—"}
                      </TableCell>
                      <TableCell
                        style={{
                          fontFamily: "var(--font-mono)",
                          fontSize: 11,
                          maxWidth: 200,
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap",
                        }}
                      >
                        {log.afterState ?? "—"}
                      </TableCell>
                      <TableCell
                        style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}
                      >
                        {log.ip}
                      </TableCell>
                    </TableRow>
                  ))}
                </Table>
                <Pagination
                  page={data.page}
                  pageSize={data.pageSize}
                  total={data.total}
                  hasNext={data.hasNext}
                  onPageChange={setPage}
                />
              </>
            )}
          </>
        )}
      </PaperCard>
    </div>
  );
}
