import { redirect } from "next/navigation";
import Link from "next/link";

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 } from "@/modules/core/server/permissions";
import { listSettingsOrganizations } from "@/modules/core/server/settings";
import {
  OrganizationManagementClient,
  OrganizationRowActions,
} from "@/modules/settings/components/OrganizationManagementClient";
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 OrganizationsPageProps = {
  searchParams?: Promise<SearchParams>;
};

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

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

  const pagePath = getWorkspaceHref(context.organization?.slug, "/settings/organizations");
  const params = (await searchParams) ?? {};
  const query = getSearchParam(params, "q");
  const page = getPage(params);
  const organizationScopeId = context.account.platformRoleId ? undefined : context.organization?.id;
  const organizations = await listSettingsOrganizations(organizationScopeId ? { organizationId: organizationScopeId } : {});
  const normalizedQuery = query.trim().toLowerCase();
  const filteredOrganizations = organizations.filter((organization) =>
    [organization.name, organization.slug, organization.status].join(" ").toLowerCase().includes(normalizedQuery),
  );
  const pageCount = getPageCount(filteredOrganizations.length);
  const visibleOrganizations = paginate(filteredOrganizations, page);
  const canManageOrganizations = hasPermission(context.permissions, "organization:manage");
  const canInviteMembers = hasPermission(context.permissions, "account:manage");
  const organizationRoleGroups = await Promise.all(
    visibleOrganizations.map(async (organization) => ({
      organizationId: organization.id,
      roles: await getRoleDefinitions(organization.id),
    })),
  );
  const rolesByOrganizationId = new Map(
    organizationRoleGroups.map((group) => [group.organizationId, group.roles]),
  );

  return (
    <div className="flex flex-col gap-5">
      {canManageOrganizations ? (
        <div className="flex justify-end">
          <OrganizationManagementClient />
        </div>
      ) : null}

      <Card>
        <CardHeader>
          <CardTitle>机构列表</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <TableToolbar
            pathname={pagePath}
            query={query}
            searchPlaceholder="搜索机构名称、标识、状态"
            total={filteredOrganizations.length}
          />
          <div className="overflow-x-auto">
            <Table className="w-full min-w-[820px] 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">Slug</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.Head className="px-4 py-3 text-right font-medium">操作</Table.Head>
                </Table.Row>
              </Table.Header>
              <Table.Body className="divide-y bg-card">
                {visibleOrganizations.map((organization) => (
                  <Table.Row className="table-row-enter hover:bg-secondary/45" key={organization.id}>
                    <Table.Cell className="px-4 py-3">
                      <Link
                        className="font-medium text-primary underline-offset-4 hover:underline"
                        href={getWorkspaceHref(context.organization?.slug, `/settings/organizations/${organization.id}`)}
                      >
                        {organization.name}
                      </Link>
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3 text-muted-foreground">{organization.slug}</Table.Cell>
                    <Table.Cell className="px-4 py-3">{organization.status === "active" ? "启用" : "停用"}</Table.Cell>
                    <Table.Cell className="px-4 py-3 text-right text-muted-foreground">
                      {new Date(organization.createdAt).toLocaleString("zh-CN")}
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">
                      <OrganizationRowActions
                        canInvite={canInviteMembers}
                        organization={organization}
                        roles={rolesByOrganizationId.get(organization.id) ?? []}
                      />
                    </Table.Cell>
                  </Table.Row>
                ))}
                {visibleOrganizations.length === 0 ? (
                  <Table.Row>
                    <Table.Cell className="px-4 py-8 text-center text-muted-foreground" colSpan={5}>
                      暂无匹配机构
                    </Table.Cell>
                  </Table.Row>
                ) : null}
              </Table.Body>
            </Table>
          </div>
          <TablePagination
            page={Math.min(page, pageCount)}
            pageCount={pageCount}
            pathname={pagePath}
            query={query}
            total={filteredOrganizations.length}
          />
        </CardContent>
      </Card>
    </div>
  );
}
