import { notFound, redirect } from "next/navigation";
import { ArrowLeft, Building2, Users } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { LinkButton } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table } from "@/components/ui/table";
import { getCurrentAuthContext, toPublicAccount } from "@/modules/core/server/auth";
import { getRoleDefinitions, hasPermission } from "@/modules/core/server/permissions";
import {
  listSettingsAccounts,
  listSettingsJoinRequests,
  listSettingsMemberships,
  listSettingsOrganizationInvitations,
  listSettingsOrganizations,
} from "@/modules/core/server/settings";
import { OrganizationDetailClient } from "@/modules/settings/components/OrganizationDetailClient";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

type OrganizationDetailPageProps = {
  params: Promise<{
    id: string;
  }>;
};

export default async function OrganizationDetailPage({
  params,
}: OrganizationDetailPageProps): Promise<React.ReactElement> {
  const context = await getCurrentAuthContext();
  if (!context) {
    redirect("/login");
  }

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

  const { id } = await params;
  const organizations = await listSettingsOrganizations({ organizationId: id });
  const organization = organizations[0];
  if (!organization) {
    notFound();
  }

  if (!context.account.platformRoleId && context.organization?.id && context.organization.id !== organization.id) {
    redirect(getWorkspaceHref(context.organization?.slug, "/settings/organizations"));
  }

  const [roles, organizationMemberships, organizationAccounts, invitations, joinRequests] = await Promise.all([
    getRoleDefinitions(organization.id),
    listSettingsMemberships({ organizationId: organization.id }),
    listSettingsAccounts({ organizationId: organization.id }),
    listSettingsOrganizationInvitations({ organizationId: organization.id }),
    listSettingsJoinRequests({ organizationId: organization.id }),
  ]);
  const accountById = new Map(organizationAccounts.map((account) => [account.id, account]));
  const members = organizationMemberships
    .map((membership) => {
      const account = accountById.get(membership.accountId);
      if (!account) {
        return null;
      }

      return {
        account: toPublicAccount(account, membership.roleKey, organization),
        membership,
      };
    })
    .filter((item): item is NonNullable<typeof item> => item !== null);
  const pendingRequests = joinRequests.filter((request) => request.status === "pending");

  return (
    <div className="flex flex-col gap-5">
      <section className="flex flex-col gap-4 border-b pb-5 lg:flex-row lg:items-end lg:justify-between">
        <div>
          <LinkButton href={getWorkspaceHref(context.organization?.slug, "/settings/organizations")} size="sm" variant="outline">
            <ArrowLeft className="size-4" aria-hidden="true" />
            返回机构列表
          </LinkButton>
          <div className="mt-5 flex items-center gap-3">
            <span className="inline-flex size-11 items-center justify-center rounded-md bg-secondary text-primary">
              <Building2 className="size-5" aria-hidden="true" />
            </span>
            <div>
              <h2 className="text-2xl font-semibold">{organization.name}</h2>
              <p className="text-sm text-muted-foreground">{organization.slug}</p>
            </div>
          </div>
        </div>
        <div className="flex flex-wrap gap-2">
          <Badge variant={organization.status === "active" ? "success" : "danger"}>
            {organization.status === "active" ? "启用" : "停用"}
          </Badge>
          <Badge variant={organization.registrationEnabled ? "success" : "secondary"}>
            {organization.registrationEnabled ? "开放注册" : "关闭注册"}
          </Badge>
          <Badge variant={organization.oidcEnabled ? "success" : "secondary"}>
            {organization.oidcEnabled ? "OIDC 已启用" : "OIDC 未启用"}
          </Badge>
        </div>
      </section>

      <section className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl">{members.length}</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 text-sm text-muted-foreground">成员</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl">{roles.filter((role) => role.scope === "organization").length}</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 text-sm text-muted-foreground">机构角色</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl">{pendingRequests.length}</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 text-sm text-muted-foreground">待审批申请</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl">{invitations.filter((invitation) => invitation.status === "active").length}</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 text-sm text-muted-foreground">有效邀请</CardContent>
        </Card>
      </section>

      <OrganizationDetailClient invitations={invitations} organization={organization} roles={roles} />

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Users className="size-4 text-primary" aria-hidden="true" />
            机构成员
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table className="w-full min-w-[760px] 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 text-right font-medium">加入时间</Table.Head>
                </Table.Row>
              </Table.Header>
              <Table.Body className="divide-y bg-card">
                {members.map(({ account, membership }) => (
                  <Table.Row className="hover:bg-secondary/45" key={membership.id}>
                    <Table.Cell className="px-4 py-3">
                      <p className="font-medium">{account.name}</p>
                      <p className="text-xs text-muted-foreground">{account.email}</p>
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">{membership.roleLabel}</Table.Cell>
                    <Table.Cell className="px-4 py-3">{membership.status}</Table.Cell>
                    <Table.Cell className="px-4 py-3">{account.status}</Table.Cell>
                    <Table.Cell className="px-4 py-3 text-right text-muted-foreground">
                      {new Date(membership.createdAt).toLocaleString("zh-CN")}
                    </Table.Cell>
                  </Table.Row>
                ))}
                {members.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>
        </CardContent>
      </Card>
    </div>
  );
}
