"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ChevronDown, Moon, Sun, ChevronRight, Menu, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { useColorMode } from "@/components/providers/ColorModeProvider";
import { Button } from "@/src/shared/ui";
import {
  HEALTHCARE_PORTALS,
  navForPortal,
  type HealthcarePortalId,
  detectPortal,
} from "@/src/modules/healthcare/constants/portals";

function isActive(pathname: string, href: string) {
  const base = href.split("?")[0];
  return pathname === base || pathname.startsWith(`${base}/`);
}

export function HealthcarePortalShell({
  children,
  portalId,
  title,
}: {
  children: React.ReactNode;
  portalId: HealthcarePortalId;
  title?: string;
}) {
  const pathname = usePathname();
  const { mode, toggle } = useColorMode();
  const [openGroups, setOpenGroups] = useState<Record<string, boolean>>({});
  const [mobileOpen, setMobileOpen] = useState(false);
  const nav = navForPortal(portalId);
  const portalMeta = HEALTHCARE_PORTALS.find((p) => p.id === portalId);

  const autoOpen = useMemo(() => {
    const map: Record<string, boolean> = {};
    for (const g of nav) {
      if (g.href && isActive(pathname, g.href)) map[g.id] = true;
      if (g.items?.some((i) => isActive(pathname, i.href))) map[g.id] = true;
    }
    return map;
  }, [pathname, nav]);

  const expanded = { ...autoOpen, ...openGroups };

  const sidebar = (
    <>
      <div className="mb-4 px-2">
        <p className="text-xs text-[var(--muted)]">تربت هلث</p>
        <p className="font-semibold text-secondary">{title ?? portalMeta?.label}</p>
      </div>
      <nav className="space-y-0.5">
        {nav.map((group) => {
          const Icon = group.icon;
          const hasChildren = !!group.items?.length;
          const groupActive = group.href
            ? isActive(pathname, group.href)
            : group.items?.some((i) => isActive(pathname, i.href));
          const isOpen = expanded[group.id] ?? false;

          if (!hasChildren && group.href) {
            return (
              <Link
                key={group.id}
                href={group.href}
                onClick={() => setMobileOpen(false)}
                className={cn(
                  "flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-all duration-200",
                  groupActive
                    ? "bg-[var(--health-accent)] text-white shadow-[var(--shadow-sm)]"
                    : "text-[var(--muted)] hover:bg-[var(--surface-muted)] hover:text-secondary"
                )}
              >
                <Icon className="h-4 w-4 shrink-0" />
                {group.label}
              </Link>
            );
          }

          return (
            <div key={group.id}>
              <button
                type="button"
                onClick={() =>
                  setOpenGroups((prev) => ({ ...prev, [group.id]: !(expanded[group.id] ?? false) }))
                }
                className={cn(
                  "flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors",
                  groupActive
                    ? "bg-[var(--surface-muted)] text-secondary"
                    : "text-[var(--muted)] hover:bg-[var(--surface-muted)]"
                )}
              >
                <Icon className="h-4 w-4 shrink-0" />
                <span className="flex-1 text-right">{group.label}</span>
                <ChevronDown className={cn("h-4 w-4 transition-transform", isOpen && "rotate-180")} />
              </button>
              {isOpen ? (
                <div className="mb-1 mr-3 space-y-0.5 border-r border-[var(--border)] pr-2">
                  {group.items?.map((item) => (
                    <Link
                      key={item.href}
                      href={item.href}
                      onClick={() => setMobileOpen(false)}
                      className={cn(
                        "block rounded-lg px-3 py-1.5 text-xs font-medium transition-colors",
                        isActive(pathname, item.href)
                          ? "bg-[var(--health-accent)] text-white"
                          : "text-[var(--muted)] hover:bg-[var(--surface-muted)]"
                      )}
                    >
                      {item.label}
                    </Link>
                  ))}
                </div>
              ) : null}
            </div>
          );
        })}
      </nav>
      <div className="mt-6 space-y-2 border-t border-[var(--border)] pt-4">
        <Link
          href="/healthcare/hub"
          className="flex items-center gap-2 px-3 text-xs text-[var(--muted)] hover:text-secondary"
        >
          <ChevronRight className="h-3.5 w-3.5" />
          تغییر پورتال
        </Link>
        <Link href="/dashboard" className="flex items-center gap-2 px-3 text-xs text-[var(--muted)] hover:text-secondary">
          <ChevronRight className="h-3.5 w-3.5" />
          workspace
        </Link>
      </div>
    </>
  );

  return (
    <div className="flex min-h-[calc(100vh-4rem)] bg-[var(--canvas)]">
      <aside className="sticky top-16 hidden h-[calc(100vh-4rem)] w-72 shrink-0 overflow-y-auto border-l border-[var(--border)] bg-[var(--surface)] p-4 lg:block">
        <div className="mb-3 flex justify-end">
          <Button type="button" variant="ghost" size="icon" onClick={toggle} aria-label="تغییر تم">
            {mode === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
          </Button>
        </div>
        {sidebar}
      </aside>

      {mobileOpen ? (
        <div className="fixed inset-0 z-50 lg:hidden">
          <button
            type="button"
            className="absolute inset-0 bg-black/40"
            aria-label="بستن منو"
            onClick={() => setMobileOpen(false)}
          />
          <aside className="absolute right-0 top-0 h-full w-80 max-w-[85vw] overflow-y-auto border-l border-[var(--border)] bg-[var(--surface)] p-4 shadow-[var(--shadow-lg)]">
            <div className="mb-4 flex items-center justify-between">
              <p className="font-semibold">{portalMeta?.label}</p>
              <Button type="button" variant="ghost" size="icon" onClick={() => setMobileOpen(false)}>
                <X className="h-5 w-5" />
              </Button>
            </div>
            {sidebar}
          </aside>
        </div>
      ) : null}

      <div className="min-w-0 flex-1">
        <div className="sticky top-16 z-30 flex items-center gap-3 border-b border-[var(--border)] bg-[var(--surface)]/95 px-4 py-3 backdrop-blur lg:hidden">
          <Button type="button" variant="outline" size="icon" onClick={() => setMobileOpen(true)}>
            <Menu className="h-5 w-5" />
          </Button>
          <p className="text-sm font-semibold text-secondary">{portalMeta?.label}</p>
        </div>
        <div className="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:pb-8">{children}</div>
      </div>
    </div>
  );
}

export function useCurrentHealthcarePortal(): HealthcarePortalId | null {
  const pathname = usePathname();
  return detectPortal(pathname);
}
