import { redirect } from "next/navigation";

import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table } from "@/components/ui/table";
import { checkDatabaseConnection } from "@/modules/core/server/db";
import { getCurrentAuthContext } from "@/modules/core/server/auth";
import { hasPermission } from "@/modules/core/server/permissions";
import {
  countSettingsBeds,
  listSettingsAccounts,
  listSettingsIncidents,
  listSettingsOrganizations,
} from "@/modules/core/server/settings";
import { IncidentStatusActions } from "@/modules/settings/components/IncidentStatusActions";
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 StatusPageProps = {
  searchParams?: Promise<SearchParams>;
};

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

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

  const pagePath = getWorkspaceHref(context.organization?.slug, "/settings/status");
  const params = (await searchParams) ?? {};
  const query = getSearchParam(params, "q");
  const page = getPage(params);
  const organizationScopeId = context.account.platformRoleId ? undefined : context.organization?.id;
  const scopeParams = organizationScopeId ? { organizationId: organizationScopeId } : {};
  const [organizations, accounts, bedCount, incidents, databaseHealth] = await Promise.all([
    listSettingsOrganizations(scopeParams),
    listSettingsAccounts(scopeParams),
    countSettingsBeds(scopeParams),
    listSettingsIncidents(scopeParams),
    checkDatabaseConnection(),
  ]);
  const canManageIncidents = hasPermission(context.permissions, "incident:manage");
  const normalizedQuery = query.trim().toLowerCase();
  const filteredIncidents = incidents.filter((incident) =>
    [incident.title, incident.description, incident.source, incident.severity, incident.status]
      .join(" ")
      .toLowerCase()
      .includes(normalizedQuery),
  );
  const pageCount = getPageCount(filteredIncidents.length);
  const visibleIncidents = paginate(filteredIncidents, page);

  return (
    <div className="flex flex-col gap-5">
      <section className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <p className="text-sm text-muted-foreground">{databaseHealth.reason}</p>
        <Badge variant={databaseHealth.ok ? "success" : "danger"}>{databaseHealth.ok ? "Healthy" : "Degraded"}</Badge>
      </section>

      <section className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl">{organizations.length}</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 text-sm text-muted-foreground">机构</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl">{accounts.length}</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 text-sm text-muted-foreground">账号</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl">{bedCount}</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 text-sm text-muted-foreground">床位</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="text-3xl">{incidents.length}</CardTitle>
          </CardHeader>
          <CardContent className="pt-0 text-sm text-muted-foreground">故障事件</CardContent>
        </Card>
      </section>

      <Card>
        <CardHeader>
          <CardTitle>故障中心</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <TableToolbar
            pathname={pagePath}
            query={query}
            searchPlaceholder="搜索故障标题、来源、状态"
            total={filteredIncidents.length}
          />
          <div className="overflow-x-auto">
            <Table className="w-full min-w-[960px] 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.Head className="px-4 py-3 text-right font-medium">操作</Table.Head>
                </Table.Row>
              </Table.Header>
              <Table.Body className="divide-y bg-card">
                {visibleIncidents.map((incident) => (
                  <Table.Row className="table-row-enter align-top hover:bg-secondary/45" key={incident.id}>
                    <Table.Cell className="px-4 py-3">
                      <p className="font-medium">{incident.title}</p>
                      <p className="text-xs text-muted-foreground">{incident.description}</p>
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">{incident.severity}</Table.Cell>
                    <Table.Cell className="px-4 py-3">{incident.status}</Table.Cell>
                    <Table.Cell className="px-4 py-3 text-muted-foreground">{incident.source}</Table.Cell>
                    <Table.Cell className="px-4 py-3 text-right text-muted-foreground">
                      {new Date(incident.createdAt).toLocaleString("zh-CN")}
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">
                      {canManageIncidents ? (
                        <IncidentStatusActions incident={incident} />
                      ) : (
                        <span className="block text-right text-xs text-muted-foreground">只读</span>
                      )}
                    </Table.Cell>
                  </Table.Row>
                ))}
                {visibleIncidents.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={filteredIncidents.length}
          />
        </CardContent>
      </Card>
    </div>
  );
}
