"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { GlobeIcon, LogOutIcon } from "lucide-react";

import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/components/ui/sidebar";
import { Typography } from "@/components/ui/typography";
import { useLogout } from "@/hooks/auth/useLogout";
import { usePermissions } from "@/hooks/auth/usePermissions";
import { useProfile } from "@/hooks/auth/useProfile";
import { useTranslation } from "@/hooks/useTranslation";
import { SUPPORTED_LANGUAGES } from "@/lib/i18n/config";
import { useI18n } from "@/lib/i18n/provider";
import { filterNavByAccess, getNavForRole } from "@/lib/constants/nav";
import { ROUTES } from "@/lib/constants/routes";
import type { UserRole } from "@/types/auth";

/**
 * Project-standard menu item sizing (same specs as Button/Input): 52px tall,
 * 12px radius, 16px logical padding, body text 14px/22px. Shared by the nav
 * routes and the footer language item so they read as one system.
 */
const MENU_ITEM_CLASSES =
  "h-13 gap-2 rounded-[12px] ps-4 pe-4 text-[14px] leading-[22px]";

/**
 * Role-driven app sidebar. Nav items come from NAV_CONFIG — pass the
 * authenticated user's role and the right menu renders.
 *
 * Direction follows the active language: English anchors it to the left,
 * Arabic to the right (the shadcn Sidebar takes a physical `side`, so this is
 * the one place we intentionally branch on `isRTL` instead of relying on
 * logical CSS).
 */
export function AppSidebar({ role }: { role: UserRole }) {
  const { t } = useTranslation();
  const { isRTL } = useI18n();
  const pathname = usePathname();
  const { setOpenMobile } = useSidebar();
  const { check } = usePermissions();
  const items = filterNavByAccess(getNavForRole(role), check);

  return (
    <Sidebar side={isRTL ? "right" : "left"} dir={isRTL ? "rtl" : "ltr"}>
      <SidebarHeader className="p-4">
        <Link
          href={items[0]?.href ?? ROUTES.HOME}
          aria-label="Washy"
          onClick={() => setOpenMobile(false)}
        >
          <Image
            src="/icon/horizontal_icon.png"
            alt="Washy"
            width={500}
            height={152}
            className="h-8 w-auto"
            priority
          />
        </Link>
      </SidebarHeader>

      <SidebarContent>
        <SidebarMenu className="gap-1 px-3">
          {items.map((item) => {
            const isActive =
              pathname === item.href || pathname.startsWith(item.href + "/");
            return (
              <SidebarMenuItem key={item.href}>
                <SidebarMenuButton
                  isActive={isActive}
                  className={MENU_ITEM_CLASSES}
                  render={<Link href={item.href} />}
                  onClick={() => setOpenMobile(false)}
                >
                  <item.icon />
                  <span>{t(item.titleKey)}</span>
                </SidebarMenuButton>
              </SidebarMenuItem>
            );
          })}
        </SidebarMenu>
      </SidebarContent>

      <SidebarFooter className="gap-1 p-3">
        <SidebarMenu>
          <SidebarMenuItem>
            <LanguageMenuItem />
          </SidebarMenuItem>
        </SidebarMenu>
        <UserFooter role={role} />
      </SidebarFooter>
    </Sidebar>
  );
}

/**
 * Language switcher styled like a nav route item (per design direction) —
 * sits above the logout/user block. Delegates all cache/refresh handling to
 * setLanguage (see the i18n provider), same as the standalone LanguageSwitcher.
 */
function LanguageMenuItem() {
  const { t, language, setLanguage } = useTranslation();

  return (
    <DropdownMenu>
      <DropdownMenuTrigger
        render={<SidebarMenuButton className={MENU_ITEM_CLASSES} />}
      >
        <GlobeIcon />
        <span>{t("common.language")}</span>
        <span className="ms-auto text-secondary-text">
          {language.toUpperCase()}
        </span>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start">
        {SUPPORTED_LANGUAGES.map((lang) => (
          <DropdownMenuItem key={lang} onClick={() => setLanguage(lang)}>
            <Typography as="span" variant="body">
              {lang === "en" ? "English" : "العربية"}
            </Typography>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

/**
 * User detail (avatar + email + role) with the logout action — shown for
 * every role at the bottom of the sidebar.
 *
 * Manual logout always asks for confirmation via ConfirmDialog; the forced
 * logout on a 401 response (axios interceptor) intentionally does not.
 */
function UserFooter({ role }: { role: UserRole }) {
  const { t } = useTranslation();
  const { data: user } = useProfile();
  const logout = useLogout();
  const [confirmLogoutOpen, setConfirmLogoutOpen] = useState(false);

  const initials =
    `${user?.firstName?.[0] ?? ""}${user?.lastName?.[0] ?? ""}`.toUpperCase();

  return (
    <div className="flex items-center gap-2 rounded-[12px] p-2">
      <Avatar>
        <AvatarFallback>{initials}</AvatarFallback>
      </Avatar>
      <div className="flex min-w-0 flex-1 flex-col">
        <Typography as="span" variant="caption" className="truncate">
          {user?.email ?? user?.phoneNumber ?? ""}
        </Typography>
        <Typography
          as="span"
          variant="caption"
          color="secondary"
          className="truncate"
        >
          {t(`roles.${user?.role ?? role}`)}
        </Typography>
      </div>
      <Button
        variant="ghost"
        size="icon-sm"
        onClick={() => setConfirmLogoutOpen(true)}
        aria-label={t("auth.logout")}
      >
        <LogOutIcon className="rtl:-scale-x-100" />
      </Button>
      <ConfirmDialog
        open={confirmLogoutOpen}
        onOpenChange={setConfirmLogoutOpen}
        title={t("auth.logoutConfirm.title")}
        description={t("auth.logoutConfirm.description")}
        icon={<LogOutIcon className="rtl:-scale-x-100" />}
        confirmLabel={t("auth.logout")}
        destructive
        onConfirm={logout}
      />
    </div>
  );
}
