'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { cn } from '@/app/_lib/utils';
import { Skeleton } from './ui/skeleton';
import { Avatar, AvatarFallback } from './ui/avatar';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from './ui/dropdown-menu';
import { PORTAL_THEMES, type PortalTheme, initials } from './portal-theme';
import { ChevronsUpDown, LogOut } from 'lucide-react';

export interface PortalNavItem {
  href: string;
  label: string;
  icon: React.ReactNode;
}

interface PortalUser {
  name?: string | null;
  email?: string | null;
  role?: string | null;
  subtitle?: string | null;
}

interface PortalShellProps {
  portalName: string;
  theme: PortalTheme;
  navItems: PortalNavItem[];
  user?: PortalUser;
  /** Optional scope indicator (e.g. <ScopeCard/>) rendered below the brand */
  scope?: React.ReactNode;
  loading: boolean;
  authed: boolean;
  onLogout: () => void;
  children: React.ReactNode;
}

export function PortalShell({
  portalName, theme, navItems, user, scope, loading, authed, onLogout, children,
}: PortalShellProps) {
  const pathname = usePathname();
  const t = PORTAL_THEMES[theme];

  return (
    <div className="flex h-screen overflow-hidden">
      {/* Sidebar */}
      <aside className="w-60 shrink-0 flex flex-col border-r bg-sidebar">
        {/* Brand */}
        <div className="h-16 flex items-center gap-3 px-5 border-b">
          <div className={cn('size-8 rounded-lg flex items-center justify-center text-white font-bold text-sm shadow-sm', t.gradient)}>
            T
          </div>
          <div className="flex flex-col leading-none">
            <span className="font-semibold text-sm tracking-tight">TOWER</span>
            <span className="text-[11px] text-muted-foreground mt-0.5">{portalName}</span>
          </div>
        </div>

        {/* Scope */}
        {!loading && authed && scope}

        {/* Nav */}
        <nav className="flex-1 overflow-y-auto p-3 space-y-1">
          {loading ? (
            <div className="space-y-2 p-1">
              {Array.from({ length: navItems.length }).map((_, i) => <Skeleton key={i} className="h-9 w-full" />)}
            </div>
          ) : (
            navItems.map((item) => {
              // Portal root (e.g. /admin, /org) is a single segment — match exactly so it
              // doesn't stay highlighted on sub-routes. Deeper items match by prefix.
              const isRoot = item.href.split('/').filter(Boolean).length === 1;
              const isActive = isRoot
                ? pathname === item.href
                : pathname === item.href || pathname.startsWith(item.href + '/');
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={cn(
                    'group relative flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors',
                    isActive
                      ? cn(t.activeBg, t.activeText, 'font-medium')
                      : 'text-muted-foreground hover:bg-accent hover:text-foreground',
                  )}
                >
                  {isActive && <span className={cn('absolute left-0 top-1/2 -translate-y-1/2 h-5 w-1 rounded-r-full', t.bar)} />}
                  <span className="size-4 shrink-0 [&_svg]:size-4">{item.icon}</span>
                  {item.label}
                </Link>
              );
            })
          )}
        </nav>

        {/* User */}
        <div className="p-3 border-t">
          {loading ? (
            <div className="flex items-center gap-3 px-1">
              <Skeleton className="size-9 rounded-full" />
              <div className="flex-1 space-y-1.5">
                <Skeleton className="h-3 w-24" />
                <Skeleton className="h-2.5 w-16" />
              </div>
            </div>
          ) : user ? (
            <DropdownMenu>
              <DropdownMenuTrigger className="w-full flex items-center gap-3 rounded-lg p-2 hover:bg-accent transition-colors text-left outline-none">
                <Avatar>
                  <AvatarFallback className={cn(t.gradient, 'text-white')}>{initials(user.name, user.email)}</AvatarFallback>
                </Avatar>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium truncate">{user.name ?? user.email}</p>
                  <p className="text-xs text-muted-foreground truncate">{user.subtitle ?? user.role ?? user.email}</p>
                </div>
                <ChevronsUpDown className="size-4 text-muted-foreground shrink-0" />
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" side="top" className="w-52">
                <DropdownMenuLabel className="flex flex-col">
                  <span className="text-sm truncate">{user.name ?? user.email}</span>
                  <span className="text-xs font-normal text-muted-foreground truncate">{user.email}</span>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={onLogout} className="text-destructive focus:text-destructive">
                  <LogOut className="size-4" />
                  Sign out
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          ) : null}
        </div>
      </aside>

      {/* Main */}
      <main className="flex-1 overflow-auto bg-muted/30">
        {!loading && authed ? (
          <div className="p-6 lg:p-8 max-w-6xl mx-auto w-full">{children}</div>
        ) : (
          <div className="p-8 space-y-4">
            <Skeleton className="h-8 w-48" />
            <div className="grid grid-cols-4 gap-4">
              {Array.from({ length: 4 }).map((_, i) => <Skeleton key={i} className="h-24" />)}
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
