"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { ChevronRight } from "lucide-react";

type BreadcrumbItem = {
  href?: string;
  label: string;
};

const routeLabels: Record<string, string> = {
  "/app/dashboard": "运营看板",
  "/app/elders": "老人档案",
  "/app/beds": "床位房间",
  "/app/health": "健康照护",
  "/app/care": "护理服务",
  "/app/emergency": "安全应急",
  "/app/devices": "设备运维",
  "/app/notices": "公告通知",
  "/app/alerts": "规则预警",
  "/app/family": "家属服务",
  "/app/settings/global": "全局配置",
  "/app/settings/organizations": "机构管理",
  "/app/settings/users": "用户管理",
  "/app/settings/roles": "角色权限",
  "/app/settings/audit": "审计日志",
  "/app/settings/status": "运行状态",
};

function getBreadcrumbs(pathname: string): BreadcrumbItem[] {
  if (pathname === "/app" || pathname === "/app/dashboard") {
    return [{ label: "工作台" }];
  }

  if (pathname.startsWith("/app/settings/organizations/")) {
    return [
      { href: "/app/dashboard", label: "工作台" },
      { href: "/app/settings/users", label: "系统设置" },
      { href: "/app/settings/organizations", label: "机构管理" },
      { label: "机构详情" },
    ];
  }

  if (pathname.startsWith("/app/settings")) {
    return [
      { href: "/app/dashboard", label: "工作台" },
      { href: "/app/settings/users", label: "系统设置" },
      { label: routeLabels[pathname] ?? "设置" },
    ];
  }

  return [
    { href: "/app/dashboard", label: "工作台" },
    { label: routeLabels[pathname] ?? "工作区" },
  ];
}

export function AppBreadcrumbs(): React.ReactElement {
  const pathname = usePathname();
  const breadcrumbs = getBreadcrumbs(pathname);

  return (
    <nav aria-label="面包屑" className="flex min-w-0 items-center gap-1 text-sm">
      {breadcrumbs.map((item, index) => {
        const isLast = index === breadcrumbs.length - 1;

        return (
          <span className="flex min-w-0 items-center gap-1" key={`${item.label}-${index}`}>
            {index > 0 ? <ChevronRight className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" /> : null}
            {item.href && !isLast ? (
              <Link className="shrink-0 font-medium hover:text-primary" href={item.href}>
                {item.label}
              </Link>
            ) : (
              <span className={isLast ? "min-w-0 truncate text-muted-foreground" : "shrink-0 font-medium"}>{item.label}</span>
            )}
          </span>
        );
      })}
    </nav>
  );
}
