import { redirect } from "next/navigation";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table } from "@/components/ui/table";
import { listAuditLogs } from "@/modules/core/server/audit";
import { getCurrentAuthContext } from "@/modules/core/server/auth";
import { hasPermission } from "@/modules/core/server/permissions";
import { TablePagination, TableToolbar } from "@/modules/settings/components/TableToolbar";
import { getPage, getPageCount, getSearchParam, paginate, type SearchParams } from "@/modules/settings/lib/pagination";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

type AuditPageProps = {
  searchParams?: Promise<SearchParams>;
};

export default async function AuditPage({ searchParams }: AuditPageProps): Promise<React.ReactElement> {
  const context = await getCurrentAuthContext();
  if (!context) {
    redirect("/login");
  }

  if (!hasPermission(context.permissions, "audit:read")) {
    redirect(getWorkspaceHref(context.organization?.slug, "/dashboard"));
  }

  const pagePath = getWorkspaceHref(context.organization?.slug, "/settings/audit");
  const params = (await searchParams) ?? {};
  const query = getSearchParam(params, "q");
  const page = getPage(params);
  const logs = await listAuditLogs({
    organizationId: context.account.platformRoleId ? undefined : context.organization?.id,
    limit: 100,
  });
  const normalizedQuery = query.trim().toLowerCase();
  const filteredLogs = logs.filter((log) =>
    [log.actorEmail ?? "系统", log.action, log.targetType, log.targetId ?? "", log.result, log.reason]
      .join(" ")
      .toLowerCase()
      .includes(normalizedQuery),
  );
  const pageCount = getPageCount(filteredLogs.length);
  const visibleLogs = paginate(filteredLogs, page);

  return (
    <div className="flex flex-col gap-5">
      <Card>
        <CardHeader>
          <CardTitle>审计列表</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <TableToolbar
            pathname={pagePath}
            query={query}
            searchPlaceholder="搜索操作者、动作、对象、结果"
            total={filteredLogs.length}
          />
          <div className="overflow-x-auto">
            <Table className="w-full min-w-[900px] text-sm">
              <Table.Header className="bg-secondary text-left text-xs text-muted-foreground">
                <Table.Row>
                  <Table.Head className="px-4 py-3 font-medium">时间</Table.Head>
                  <Table.Head className="px-4 py-3 font-medium">操作者</Table.Head>
                  <Table.Head className="px-4 py-3 font-medium">动作</Table.Head>
                  <Table.Head className="px-4 py-3 font-medium">对象</Table.Head>
                  <Table.Head className="px-4 py-3 font-medium">结果</Table.Head>
                  <Table.Head className="px-4 py-3 font-medium">原因</Table.Head>
                </Table.Row>
              </Table.Header>
              <Table.Body className="divide-y bg-card">
                {visibleLogs.map((log) => (
                  <Table.Row className="table-row-enter hover:bg-secondary/45" key={log.id}>
                    <Table.Cell className="px-4 py-3 text-muted-foreground">{new Date(log.timestamp).toLocaleString("zh-CN")}</Table.Cell>
                    <Table.Cell className="px-4 py-3">{log.actorEmail ?? "系统"}</Table.Cell>
                    <Table.Cell className="px-4 py-3">{log.action}</Table.Cell>
                    <Table.Cell className="px-4 py-3 text-muted-foreground">
                      {log.targetType}
                      {log.targetId ? ` / ${log.targetId.slice(0, 8)}` : ""}
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">{log.result}</Table.Cell>
                    <Table.Cell className="px-4 py-3 text-muted-foreground">{log.reason}</Table.Cell>
                  </Table.Row>
                ))}
                {visibleLogs.length === 0 ? (
                  <Table.Row>
                    <Table.Cell className="px-4 py-8 text-center text-muted-foreground" colSpan={6}>
                      暂无匹配审计
                    </Table.Cell>
                  </Table.Row>
                ) : null}
              </Table.Body>
            </Table>
          </div>
          <TablePagination
            page={Math.min(page, pageCount)}
            pageCount={pageCount}
            pathname={pagePath}
            query={query}
            total={filteredLogs.length}
          />
        </CardContent>
      </Card>
    </div>
  );
}
