import { redirect } from "next/navigation";
import { Activity, FileText, HeartPulse, ShieldAlert, Stethoscope } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table } from "@/components/ui/table";
import { getCurrentAuthContext } from "@/modules/core/server/auth";
import { hasPermission } from "@/modules/core/server/permissions";
import { HealthAdminClient } from "@/modules/health/components/HealthAdminClient";
import { listHealthAdminData } from "@/modules/health/server/operations";
import type { HealthReviewSeverity, HealthReviewStatus } from "@/modules/health/types";
import {
  CHRONIC_CONDITION_STATUS_LABELS,
  HEALTH_REVIEW_SEVERITY_LABELS,
  HEALTH_REVIEW_STATUS_LABELS,
  VITAL_SOURCE_LABELS,
} from "@/modules/health/types";
import { getWorkspaceHref } from "@/modules/shared/lib/workspace-routing";

type HealthPageData = {
  canManage: boolean;
  data: Awaited<ReturnType<typeof listHealthAdminData>>;
};

function formatDateTime(value: string | undefined): string {
  return value ? new Date(value).toLocaleString("zh-CN") : "-";
}

function formatTenths(value: number | undefined, suffix = ""): string {
  return value === undefined ? "-" : `${(value / 10).toFixed(1)}${suffix}`;
}

function severityBadgeVariant(severity: HealthReviewSeverity): "secondary" | "warning" | "danger" {
  if (severity === "critical") {
    return "danger";
  }

  return severity === "warning" ? "warning" : "secondary";
}

function reviewStatusBadgeVariant(status: HealthReviewStatus): "success" | "secondary" | "warning" {
  if (status === "pending") {
    return "warning";
  }

  return status === "resolved" ? "success" : "secondary";
}

async function loadHealthPageData(): Promise<HealthPageData> {
  const context = await getCurrentAuthContext();
  if (!context) {
    redirect("/login");
  }

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

  const organizationId = context.organization?.id;
  if (!organizationId) {
    redirect(getWorkspaceHref(context.organization?.slug, "/dashboard"));
  }

  const data = await listHealthAdminData(organizationId);
  return {
    canManage: hasPermission(context.permissions, "health:manage"),
    data,
  };
}

export async function renderHealthWorkspacePage(): Promise<React.ReactElement> {
  const { data } = await loadHealthPageData();
  const pendingReviews = data.reviews.filter((review) => review.status === "pending").slice(0, 8);
  const recentVitals = data.vitals.slice(0, 8);
  const activeConditions = data.chronicConditions.filter((condition) => condition.status === "active").slice(0, 8);

  return (
    <div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
      <section className="flex flex-col gap-3 border-b pb-4 lg:flex-row lg:items-start lg:justify-between">
        <div className="flex min-w-0 items-center gap-3">
          <span className="inline-flex size-9 items-center justify-center rounded-md bg-secondary text-primary">
            <HeartPulse className="size-4" aria-hidden="true" />
          </span>
          <div className="min-w-0">
            <h1 className="truncate text-xl font-semibold tracking-normal">健康照护</h1>
            <p className="mt-1 truncate text-sm text-muted-foreground">健康概览、重点慢病、生命体征与异常复核队列</p>
          </div>
        </div>
      </section>

      <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <MetricCard icon={<FileText className="size-4" aria-hidden="true" />} label="健康档案" value={data.metrics.eldersWithProfiles} />
        <MetricCard icon={<Activity className="size-4" aria-hidden="true" />} label="今日体征" value={data.metrics.vitalsToday} />
        <MetricCard icon={<Stethoscope className="size-4" aria-hidden="true" />} label="慢病管理" value={data.metrics.activeChronicConditions} />
        <MetricCard icon={<ShieldAlert className="size-4" aria-hidden="true" />} label="待复核" value={data.metrics.pendingReviews} />
      </section>

      <section className="grid gap-4 xl:grid-cols-[1.1fr_0.9fr]">
        <Card>
          <CardHeader>
            <CardTitle>待复核健康异常</CardTitle>
            <CardDescription>按最新异常记录展示护理复核队列。</CardDescription>
          </CardHeader>
          <CardContent className="overflow-x-auto">
            <Table className="w-full min-w-[720px] 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.Row>
              </Table.Header>
              <Table.Body className="divide-y bg-card">
                {pendingReviews.map((review) => (
                  <Table.Row key={review.id}>
                    <Table.Cell className="px-4 py-3 font-medium">{review.elderName}</Table.Cell>
                    <Table.Cell className="px-4 py-3">
                      <p className="font-medium">{review.title}</p>
                      <p className="text-xs text-muted-foreground">{review.description}</p>
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">
                      <Badge variant={severityBadgeVariant(review.severity)}>
                        {HEALTH_REVIEW_SEVERITY_LABELS[review.severity]}
                      </Badge>
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3">
                      <Badge variant={reviewStatusBadgeVariant(review.status)}>
                        {HEALTH_REVIEW_STATUS_LABELS[review.status]}
                      </Badge>
                    </Table.Cell>
                    <Table.Cell className="px-4 py-3 text-muted-foreground">{formatDateTime(review.createdAt)}</Table.Cell>
                  </Table.Row>
                ))}
                {pendingReviews.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>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>慢病重点关注</CardTitle>
            <CardDescription>持续管理中的慢病记录。</CardDescription>
          </CardHeader>
          <CardContent className="grid gap-2">
            {activeConditions.map((condition) => (
              <div className="rounded-md border p-3" key={condition.id}>
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <p className="truncate text-sm font-medium">{condition.elderName}</p>
                    <p className="mt-1 text-xs text-muted-foreground">{condition.name}</p>
                  </div>
                  <Badge variant="warning">{CHRONIC_CONDITION_STATUS_LABELS[condition.status]}</Badge>
                </div>
                <p className="mt-2 text-xs text-muted-foreground">{condition.followUpNotes || condition.treatmentNotes || "暂无随访备注"}</p>
              </div>
            ))}
            {activeConditions.length === 0 ? <p className="text-sm text-muted-foreground">暂无持续管理慢病记录</p> : null}
          </CardContent>
        </Card>
      </section>

      <Card>
        <CardHeader>
          <CardTitle>最近生命体征</CardTitle>
          <CardDescription>展示最新录入或采集的生命体征记录。</CardDescription>
        </CardHeader>
        <CardContent 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">时间</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 font-medium">血氧</Table.Head>
                <Table.Head className="px-4 py-3 font-medium">备注</Table.Head>
              </Table.Row>
            </Table.Header>
            <Table.Body className="divide-y bg-card">
              {recentVitals.map((vital) => (
                <Table.Row key={vital.id}>
                  <Table.Cell className="px-4 py-3 font-medium">{vital.elderName}</Table.Cell>
                  <Table.Cell className="px-4 py-3 text-muted-foreground">{formatDateTime(vital.recordedAt)}</Table.Cell>
                  <Table.Cell className="px-4 py-3">{VITAL_SOURCE_LABELS[vital.source]}</Table.Cell>
                  <Table.Cell className="px-4 py-3">
                    {vital.systolicBp && vital.diastolicBp ? `${vital.systolicBp}/${vital.diastolicBp}` : "-"}
                  </Table.Cell>
                  <Table.Cell className="px-4 py-3">{vital.heartRate?.toString() ?? "-"}</Table.Cell>
                  <Table.Cell className="px-4 py-3">{formatTenths(vital.temperatureTenths, "°C")}</Table.Cell>
                  <Table.Cell className="px-4 py-3">{vital.spo2 === undefined ? "-" : `${vital.spo2}%`}</Table.Cell>
                  <Table.Cell className="px-4 py-3 text-muted-foreground">{vital.notes || "-"}</Table.Cell>
                </Table.Row>
              ))}
              {recentVitals.length === 0 ? (
                <Table.Row>
                  <Table.Cell className="px-4 py-8 text-center text-muted-foreground" colSpan={8}>
                    暂无生命体征记录
                  </Table.Cell>
                </Table.Row>
              ) : null}
            </Table.Body>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}

export async function renderHealthSettingsPage(): Promise<React.ReactElement> {
  const { canManage, data } = await loadHealthPageData();

  return (
    <div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
      <section className="flex flex-col gap-3 border-b pb-4 lg:flex-row lg:items-start lg:justify-between">
        <div className="flex min-w-0 items-center gap-3">
          <span className="inline-flex size-9 items-center justify-center rounded-md bg-secondary text-primary">
            <HeartPulse className="size-4" aria-hidden="true" />
          </span>
          <div className="min-w-0">
            <h1 className="truncate text-xl font-semibold tracking-normal">健康数据管理</h1>
            <p className="mt-1 truncate text-sm text-muted-foreground">维护健康档案、生命体征、慢病记录与异常复核</p>
          </div>
        </div>
      </section>

      <HealthAdminClient canManage={canManage} initialData={data} />
    </div>
  );
}

function MetricCard({ icon, label, value }: { icon: React.ReactNode; label: string; value: number }): React.ReactElement {
  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0">
        <CardDescription>{label}</CardDescription>
        <span className="text-primary">{icon}</span>
      </CardHeader>
      <CardContent>
        <CardTitle className="text-3xl">{value}</CardTitle>
      </CardContent>
    </Card>
  );
}
