import { redirect } from "next/navigation";

import { getCurrentAuthContext } from "@/modules/core/server/auth";
import {
  listOperationalAdmissions,
  listOperationalBeds,
  listOperationalElders,
  listOperationalIncidents,
} from "@/modules/core/server/operations";
import { hasPermission } from "@/modules/core/server/permissions";
import type { BedStatus, Permission } from "@/modules/core/types";
import { DashboardHome, type DashboardMetric } from "@/modules/dashboard/components/DashboardHome";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

const BED_STATUSES: BedStatus[] = ["available", "occupied", "maintenance", "disabled"];
const DASHBOARD_PERMISSIONS: Permission[] = ["elder:read", "facility:read", "admission:read", "incident:read"];

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

  const organizationId = context.organization?.id;
  const canViewDashboard = DASHBOARD_PERMISSIONS.some((permission) => hasPermission(context.permissions, permission));
  if (!canViewDashboard) {
    redirect(getWorkspaceHref(context.organization?.slug, "/family"));
  }

  const [elders, beds, admissions, incidents] = await Promise.all([
    listOperationalElders(organizationId),
    listOperationalBeds(organizationId),
    listOperationalAdmissions(organizationId),
    listOperationalIncidents(organizationId),
  ]);

  const activeElders = elders.filter((elder) => elder.status === "active").length;
  const pendingElders = elders.filter((elder) => elder.status === "pending").length;
  const occupiedBeds = beds.filter((bed) => bed.status === "occupied").length;
  const availableBeds = beds.filter((bed) => bed.status === "available").length;
  const activeAdmissions = admissions.filter((admission) => admission.status === "active").length;
  const openIncidents = incidents.filter((incident) => incident.status !== "closed").length;

  const metrics: DashboardMetric[] = [
    { label: "在院老人", value: String(activeElders), trend: `待入住 ${pendingElders}`, icon: "users" },
    { label: "床位占用", value: `${occupiedBeds}/${beds.length}`, trend: `空闲 ${availableBeds}`, icon: "beds" },
    { label: "当前入住", value: String(activeAdmissions), trend: `历史 ${admissions.length}`, icon: "admissions" },
    { label: "未关闭故障", value: String(openIncidents), trend: `总计 ${incidents.length}`, icon: "incidents" },
  ];

  const occupancyData = BED_STATUSES.map((status) => ({
    label: status,
    count: beds.filter((bed) => bed.status === status).length,
  }));

  const recentAdmissions = admissions.slice(0, 6).map((admission) => ({
    id: admission.id,
    elderName: admission.elderName,
    bedLabel: `${admission.roomName}-${admission.bedCode}`,
    status: admission.status,
    admittedAt: admission.admittedAt,
    dischargedAt: admission.dischargedAt,
  }));

  const visibleIncidents = incidents
    .filter((incident) => incident.status !== "closed")
    .slice(0, 6)
    .map((incident) => ({
      id: incident.id,
      severity: incident.severity,
      status: incident.status,
      title: incident.title,
      source: incident.source,
      createdAt: incident.createdAt,
    }));

  return (
    <DashboardHome
      incidents={visibleIncidents}
      metrics={metrics}
      occupancyData={occupancyData}
      recentAdmissions={recentAdmissions}
    />
  );
}
