import Link from "next/link";
import {
  Bell,
  BedDouble,
  Building2,
  ClipboardCheck,
  Globe2,
  HeartPulse,
  LayoutDashboard,
  ListChecks,
  Radio,
  Settings,
  ShieldAlert,
  Stethoscope,
  TabletSmartphone,
  Users,
  Wrench,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";

import type { Permission, PublicAccount } from "@/modules/core/types";
import { SignOutButton } from "@/modules/auth/components/SignOutButton";
import { UserAvatar } from "@/modules/shared/components/UserAvatar";

type NavItem = {
  href: string;
  label: string;
  icon: LucideIcon;
  permission?: Permission;
};

type NavGroup = {
  label: string;
  items: NavItem[];
};

const navGroups: NavGroup[] = [
  {
    label: "运营",
    items: [
      {
        href: "/app/dashboard",
        label: "运营看板",
        icon: LayoutDashboard,
      },
      {
        href: "/app/elders",
        label: "老人档案",
        icon: Users,
      },
      {
        href: "/app/beds",
        label: "床位房间",
        icon: BedDouble,
      },
      {
        href: "/app/health",
        label: "健康照护",
        icon: HeartPulse,
      },
      {
        href: "/app/care",
        label: "护理服务",
        icon: ClipboardCheck,
      },
      {
        href: "/app/emergency",
        label: "安全应急",
        icon: ShieldAlert,
      },
    ],
  },
  {
    label: "协同",
    items: [
      {
        href: "/app/devices",
        label: "设备运维",
        icon: Wrench,
      },
      {
        href: "/app/notices",
        label: "公告通知",
        icon: Bell,
      },
      {
        href: "/app/alerts",
        label: "规则预警",
        icon: Radio,
      },
      {
        href: "/app/family",
        label: "家属服务",
        icon: TabletSmartphone,
      },
    ],
  },
  {
    label: "系统设置",
    items: [
      {
        href: "/app/settings/global",
        label: "全局配置",
        icon: Globe2,
        permission: "platform:manage",
      },
      {
        href: "/app/settings/organizations",
        label: "机构管理",
        icon: Building2,
        permission: "organization:read",
      },
      {
        href: "/app/settings/users",
        label: "用户管理",
        icon: Users,
        permission: "account:read",
      },
      {
        href: "/app/settings/roles",
        label: "角色权限",
        icon: Settings,
        permission: "role:read",
      },
      {
        href: "/app/settings/audit",
        label: "审计日志",
        icon: ListChecks,
        permission: "audit:read",
      },
      {
        href: "/app/settings/status",
        label: "运行状态",
        icon: Wrench,
        permission: "incident:read",
      },
    ],
  },
];

const navItems: NavItem[] = navGroups.flatMap((group) => group.items);

type AppShellProps = {
  children: React.ReactNode;
  account: PublicAccount;
  permissions: Permission[];
};

export function AppShell({ children, account, permissions }: AppShellProps): React.ReactElement {
  const visibleNavGroups = navGroups
    .map((group) => ({
      ...group,
      items: group.items.filter((item) => !item.permission || permissions.includes(item.permission)),
    }))
    .filter((group) => group.items.length > 0);

  return (
    <div className="flex min-h-svh items-stretch bg-background text-foreground">
      <aside className="hidden w-64 shrink-0 border-r bg-white/78 backdrop-blur xl:block">
        <div className="flex h-full min-h-0 flex-col">
          <Link href="/app/dashboard" className="flex min-h-16 items-center gap-3 border-b px-5">
            <span className="inline-flex size-10 items-center justify-center rounded-md bg-primary text-primary-foreground">
              <Stethoscope className="size-5" aria-hidden="true" />
            </span>
            <span>
              <span className="block text-base font-semibold">TeaTea 康护</span>
            </span>
          </Link>

          <nav className="min-h-0 flex-1 overflow-y-auto px-3 py-4" aria-label="主导航">
            <div className="space-y-5">
              {visibleNavGroups.map((group) => (
                <section key={group.label}>
                  <p className="px-3 pb-2 text-xs font-semibold text-muted-foreground">{group.label}</p>
                  <ul className="space-y-1">
                    {group.items.map((item) => (
                      <li key={item.href}>
                        <Link
                          href={item.href}
                          className="group flex min-h-11 items-center gap-3 rounded-md px-3 text-sm transition-colors hover:bg-secondary"
                        >
                          <item.icon
                            className="size-4 shrink-0 text-muted-foreground group-hover:text-primary"
                            aria-hidden="true"
                          />
                          <span className="min-w-0 truncate font-medium">{item.label}</span>
                        </Link>
                      </li>
                    ))}
                  </ul>
                </section>
              ))}
            </div>
          </nav>

          <div className="border-t p-3">
            <div className="flex min-w-0 items-center gap-3 rounded-md bg-secondary/55 p-2">
              <UserAvatar avatarUrl={account.avatarUrl} name={account.name} size="sm" />
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-medium leading-tight">{account.name}</p>
                <p className="truncate text-xs leading-tight text-muted-foreground">{account.email}</p>
              </div>
            </div>
            <SignOutButton className="mt-2 w-full justify-start" />
          </div>
        </div>
      </aside>

      <div className="flex min-w-0 flex-1 flex-col">
        <header className="sticky top-0 z-20 flex min-h-14 items-center justify-between border-b bg-background/88 px-4 backdrop-blur md:px-8">
          <div className="flex items-center gap-3">
            <span className="inline-flex size-10 items-center justify-center rounded-md bg-primary text-primary-foreground xl:hidden">
              <Stethoscope className="size-5" aria-hidden="true" />
            </span>
            <div>
              <p className="text-sm font-medium">工作台</p>
            </div>
          </div>
          <div className="flex min-w-0 items-center gap-2 xl:hidden">
            <div className="hidden min-w-0 items-center gap-2 sm:flex">
              <p className="min-w-0 max-w-[min(52vw,24rem)] truncate whitespace-nowrap text-right text-sm leading-tight">
                <span className="font-medium">{account.name}</span>
                <span className="ml-2 text-muted-foreground">{account.email}</span>
              </p>
              <UserAvatar avatarUrl={account.avatarUrl} name={account.name} size="sm" />
            </div>
            <SignOutButton />
          </div>
        </header>

        <main className="page-enter min-h-0 flex-1 overflow-y-auto px-4 py-5 md:px-8">{children}</main>
      </div>
    </div>
  );
}

export { navItems };
