"use client";

import { toastApiError } from "@/lib/toast-api-error";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { EllipsisVertical, LogOut, Settings, ShieldAlert, UserRound } from "lucide-react";
import {
  exitCustomerImpersonation,
  logoutCustomer,
  performLogout,
  type ImpersonationType,
} from "@/lib/auth/logout-client";
import { customerUrl, extractCustomerTenantFromPath } from "@/lib/tenant";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar";
import { getInitials } from "@/lib/utils";

type NavUserProps = {
  readonly user: {
    readonly name: string;
    readonly email: string;
    readonly avatar?: string;
  };
  readonly impersonated?: boolean;
  readonly impersonationType?: ImpersonationType | null;
  /** Explicit tenant slug — required in host mode where the path has no tenant segment. */
  readonly customerTenant?: string | null;
};

export function NavUser({
  user,
  impersonated = false,
  impersonationType = null,
  customerTenant: customerTenantProp = null,
}: NavUserProps) {
  const { isMobile } = useSidebar();
  const pathname = usePathname();
  const [busy, setBusy] = useState(false);
  const customerTenant = customerTenantProp || extractCustomerTenantFromPath(pathname);
  const settingsHref = customerTenant
    ? customerUrl(customerTenant, "/settings")
    : "/dashboard/settings";
  const type: ImpersonationType = impersonationType === "corporate" ? "corporate" : "admin";
  const exitLabel = type === "corporate" ? "Return to my account" : "Exit impersonation";

  async function handleExitImpersonation() {
    if (!customerTenant) {
      return;
    }
    setBusy(true);
    try {
      await exitCustomerImpersonation(customerTenant, type);
    } catch (error) {
      setBusy(false);
      toastApiError(error, "Could not end impersonation.");
    }
  }

  async function handleLogout() {
    setBusy(true);
    try {
      if (customerTenant) {
        await logoutCustomer(customerTenant);
        return;
      }

      await performLogout({ audience: "backend" });
    } catch (error) {
      setBusy(false);
      toastApiError(error, "Could not log out.");
    }
  }

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton
              size="lg"
              className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
              disabled={busy}
            >
              <Avatar className="h-8 w-8 rounded-lg grayscale">
                <AvatarImage src={user.avatar || undefined} alt={user.name} />
                <AvatarFallback className="rounded-lg">{getInitials(user.name)}</AvatarFallback>
              </Avatar>
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-medium">{user.name}</span>
                <span className="truncate text-muted-foreground text-xs">{user.email}</span>
              </div>
              <EllipsisVertical className="ml-auto size-4" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
            side={isMobile ? "bottom" : "right"}
            align="end"
            sideOffset={4}
          >
            <DropdownMenuLabel className="p-0 font-normal">
              <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
                <Avatar className="h-8 w-8 rounded-lg">
                  <AvatarImage src={user.avatar || undefined} alt={user.name} />
                  <AvatarFallback className="rounded-lg">{getInitials(user.name)}</AvatarFallback>
                </Avatar>
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-medium">{user.name}</span>
                  <span className="truncate text-muted-foreground text-xs">{user.email}</span>
                </div>
              </div>
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem asChild>
              <Link href={settingsHref}>
                <Settings />
                Settings
              </Link>
            </DropdownMenuItem>
            {impersonated && customerTenant ? (
              <DropdownMenuItem disabled={busy} onClick={() => void handleExitImpersonation()}>
                {type === "corporate" ? <UserRound /> : <ShieldAlert />}
                {exitLabel}
              </DropdownMenuItem>
            ) : null}
            <DropdownMenuItem disabled={busy} onClick={() => void handleLogout()}>
              <LogOut />
              Log out
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  );
}
