import { Outlet } from "react-router-dom";
import { Search } from "lucide-react";

import { Input, useAuth, getRoleDisplayName, type Role } from "@ump/shared";
import { SidebarProvider, SidebarInset, SidebarTrigger } from "@/components/ui/sidebar";
import { ApplicantDashboardSidebar } from "@/components/applicant/DashboardSidebar";

/** Initials from a full name — first + last word (e.g. "Thinh Hong Lam" → "TL"). */
function initialsOf(name: string): string {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return "?";
  const last = parts.length > 1 ? parts[parts.length - 1][0] : "";
  return (parts[0][0] + last).toUpperCase();
}

/**
 * Applicant dashboard shell — sidebar + header + routed content (<Outlet/>).
 *
 * Mirrors fe0/src/layouts/DashboardLayout.tsx, but hardcodes the applicant sidebar
 * (this is the applicant app — fe0 swapped admin-vs-applicant at runtime). The header
 * carries the SidebarTrigger + search and the current user's name/roles (moved here
 * from the sidebar). fe0's NotificationBell / UserMenu are deferred with the deep feature pages.
 */
export function DashboardLayout() {
  const { user, roles } = useAuth();
  const roleLabel = roles.map((r: Role) => getRoleDisplayName(r)).join(", ");

  return (
    <SidebarProvider>
      <div className="flex overflow-hidden h-screen w-full">
        <ApplicantDashboardSidebar />
        <SidebarInset>
          <header className="flex h-16 absolute top-0 left-0 right-0 items-center gap-4 border-b border-border bg-card px-4">
            <SidebarTrigger />
            <div className="flex-1">
              <div className="relative max-w-md">
                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input type="search" placeholder="Tìm kiếm..." className="pl-9 bg-background" />
              </div>
            </div>
            {user && (user.name || roleLabel) && (
              <div className="flex items-center gap-2.5">
                <div className="hidden text-right leading-tight sm:block">
                  <p className="truncate text-sm font-medium text-foreground">{user.name}</p>
                  {roleLabel && (
                    <p className="truncate text-xs text-muted-foreground">{roleLabel}</p>
                  )}
                </div>
                <span className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary/10 text-sm font-semibold text-primary">
                  {initialsOf(user.name || "?")}
                </span>
              </div>
            )}
          </header>
          <main className="flex-1 overflow-auto p-6 mt-12">
            <Outlet />
          </main>
        </SidebarInset>
      </div>
    </SidebarProvider>
  );
}
