import { redirect } from "next/navigation";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table } from "@/components/ui/table";
import { getCurrentAuthContext } from "@/modules/core/server/auth";
import { getRoleDefinitions, hasPermission, PERMISSION_DEFINITIONS } from "@/modules/core/server/permissions";
import { RoleManagementClient, RoleRowActions } from "@/modules/settings/components/RoleManagementClient";
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 RolesPageProps = {
  searchParams?: Promise<SearchParams>;
};

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

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

  const pagePath = getWorkspaceHref(context.organization?.slug, "/settings/roles");
  const params = (await searchParams) ?? {};
  const query = getSearchParam(params, "q");
  const page = getPage(params);
  const roles = await getRoleDefinitions(context.organization?.id);
  const normalizedQuery = query.trim().toLowerCase();
  const filteredRoles = roles.filter((role) =>
    [role.label, role.key, role.description, role.scope, ...role.permissions].join(" ").toLowerCase().includes(normalizedQuery),
  );
  const pageCount = getPageCount(filteredRoles.length);
  const visibleRoles = paginate(filteredRoles, page);
  const canManageRoles = hasPermission(context.permissions, "role:manage");

  return (
    <div className="flex flex-col gap-5">
      {canManageRoles ? (
        <div className="flex justify-end">
          <RoleManagementClient permissions={PERMISSION_DEFINITIONS} />
        </div>
      ) : null}

      <Card>
        <CardHeader>
          <CardTitle>角色列表</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <TableToolbar
            pathname={pagePath}
            query={query}
            searchPlaceholder="搜索角色、权限、说明"
            total={filteredRoles.length}
          />
          <div className="overflow-x-auto">
            <Table className="w-full min-w-[980px] 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 text-right font-medium">操作</Table.Head>
                </Table.Row>
              </Table.Header>
              <Table.Body className="divide-y bg-card">
                {visibleRoles.map((role) => (
                  <Table.Row className="table-row-enter align-top hover:bg-secondary/45" key={role.id}>
                    <Table.Cell className="px-4 py-3">
                      <p className="font-medium">{role.label}</p>
                      <p className="text-xs text-muted-foreground">{role.description}</p>
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">{role.scope === "platform" ? "平台" : "机构"}</Table.Cell>
                    <Table.Cell className="px-4 py-3">{role.isSystem ? "内置" : "自定义"}</Table.Cell>
                    <Table.Cell className="px-4 py-3">{role.isEnabled ? "启用" : "停用"}</Table.Cell>
                    <Table.Cell className="px-4 py-3 text-muted-foreground">{role.permissions.join(", ") || "-"}</Table.Cell>
                    <Table.Cell className="px-4 py-3">
                      <RoleRowActions permissions={PERMISSION_DEFINITIONS} role={role} />
                    </Table.Cell>
                  </Table.Row>
                ))}
                {visibleRoles.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={filteredRoles.length}
          />
        </CardContent>
      </Card>
    </div>
  );
}
