import NotificationList from "@/record-management/components/NotificationList";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { ChevronDown, User, Key, LogOut } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/shared/common/ui/button";
import { useTranslation } from "react-i18next";
import { FiBell, FiChevronDown } from "react-icons/fi";
import { useNavigate } from "react-router-dom";
import { useNotifications } from "@/shared/hooks/useNotification";
import { cn } from "@/shared/common/ui/fileUploader/utils";
import { useUser } from "@/shared/context/UserContext";
import {
  UI_LANGUAGE_OPTIONS,
  getUiLanguageLabel,
  getUiLanguageShortLabel,
  resolveUiLanguage,
} from "@/shared/i18n/uiLanguages";

export const ExternalPortal = ({
  mobileView = false,
  onItemClick,
}: {
  mobileView?: boolean;
  onItemClick?: () => void;
}) => {
  const { t, i18n } = useTranslation();
  const navigate = useNavigate();
  const userDetails = useUser();
  const { logout } = useAuthUser();
  const fullName = userDetails?.name?.en || t("header.user");
  const splittedName = fullName.trim().split(" ");
  const initials =
    splittedName.length === 1
      ? splittedName[0][0]
      : `${splittedName[0][0]}${splittedName[1][0]}`;

  const currentLanguage = resolveUiLanguage(i18n.language);
  const changeLanguage = (lng: string) => i18n.changeLanguage(lng);
  const handleLogout = () => {
    logout("/external-portal/signin");
  };

  const { unseenCount } = useNotifications({
    take: 10,
    skip: 0,
    orderBy: "updatedAt:DESC",
  });
  const [openNotifications, setOpenNotifications] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setOpenNotifications(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Handle navigation with optional callback for mobile
  const handleNavigation = (path: string) => {
    navigate(path);
    if (onItemClick) onItemClick();
  };

  return (
    <>
      <div
        className={`flex items-center ${
          mobileView
            ? "flex-col space-y-4 w-full"
            : "space-x-1 md:space-x-3 ml-auto"
        }`}>
        {/* Notifications */}
    
        <div
          className={`relative ${mobileView ? "w-full" : ""}`}
          ref={dropdownRef}>
          <Button
            variant="ghost"
            size={mobileView ? "default" : "icon"}
            className={cn(
              "relative text-gray-500 hover:bg-primary-50 hover:text-primary-600",
              mobileView
                ? "w-full justify-start px-4 py-3 text-base"
                : "h-8 w-8 rounded-full md:h-9 md:w-9",
              openNotifications &&
                "bg-primary-50 text-primary-700 ring-1 ring-inset ring-primary-300 dark:bg-primary-900/30 dark:text-primary-300 dark:ring-primary-700/60",
            )}
            aria-label={t("header.notifications")}
            onClick={() => setOpenNotifications((prev) => !prev)}>
            <FiBell
              className={cn(
                "h-4 w-4 transition-colors md:h-5 md:w-5",
                mobileView && "mr-3",
                openNotifications &&
                  "fill-primary-100 text-primary-700 dark:fill-primary-900/40 dark:text-primary-300",
              )}
            />
            {mobileView && <span>{t("header.notifications")}</span>}
            {unseenCount > 0 && (
              <span
                className={`absolute ${
                  mobileView ? "top-3 right-4" : "-top-1 -right-1"
                } bg-red-500 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full`}>
                {unseenCount}
              </span>
            )}
          </Button>
          {openNotifications && (
            <div
              className={
                mobileView
                  ? "fixed left-3 right-3 top-16 z-50 mt-2 max-h-[calc(100dvh-5rem)] overflow-hidden rounded-2xl border bg-white shadow-2xl"
                  : "absolute right-0 z-50 mt-2 w-[24rem] max-w-[calc(100vw-2rem)] overflow-hidden rounded-2xl border bg-white shadow-2xl"
              }>
              <NotificationList />
            </div>
          )}
        </div>
        {/* Language Switcher */}
        <DropdownMenu.Root>
          <DropdownMenu.Trigger asChild>
            <Button
              variant="ghost"
              size={mobileView ? "default" : "sm"}
              className={`${
                mobileView
                  ? "w-full justify-start px-4 py-3 text-base"
                  : "gap-1 md:gap-1.5 text-xs md:text-sm h-8 px-2 md:px-3"
              } font-medium text-gray-700 hover:bg-primary-50 hover:text-primary-600`}
              onClick={(e) => e.preventDefault()}>
              <FiChevronDown
                className={`${
                  mobileView ? "mr-3" : ""
                } h-3 w-3 md:h-4 md:w-4 opacity-50`}
              />
              <span>{getUiLanguageLabel(currentLanguage, t)}</span>
            </Button>
          </DropdownMenu.Trigger>
          <DropdownMenu.Content
            className={`w-40 bg-white shadow-xl rounded-lg p-1 z-50 ${
              mobileView ? "ml-4" : ""
            }`}
            align={mobileView ? "start" : "end"}
            sideOffset={5}>
            {UI_LANGUAGE_OPTIONS.map((lang) => (
              <DropdownMenu.Item
                key={lang.value}
                onSelect={() => {
                  changeLanguage(lang.value);
                  if (onItemClick) onItemClick();
                }}
                className={cn(
                  "flex items-center justify-between text-sm text-gray-700 hover:bg-primary-100 rounded-md px-3 py-2 cursor-pointer",
                  currentLanguage === lang.value && "bg-primary-50",
                )}
              >
                <span>{getUiLanguageLabel(lang.value, t)}</span>
                {currentLanguage === lang.value && (
                  <span className="text-xs">
                    {getUiLanguageShortLabel(lang.value, t)}
                  </span>
                )}
              </DropdownMenu.Item>
            ))}
          </DropdownMenu.Content>
        </DropdownMenu.Root>
        {/* User Menu */}
        <DropdownMenu.Root>
          <DropdownMenu.Trigger asChild>
            <Button
              variant="ghost"
              className={`flex items-center ${
                mobileView
                  ? "w-full justify-start px-4 py-3 text-base"
                  : "h-8 md:h-10 px-1 md:px-2"
              } space-x-1 md:space-x-2 text-gray-700 hover:bg-gray-100 hover:text-gray-900`}
              aria-label={t("header.userMenu")}>
              <div
                className={`flex items-center justify-center ${
                  mobileView ? "w-10 h-10" : "w-7 h-7 md:w-8 md:h-8"
                } rounded-full bg-gray-200`}>
                <span
                  className={`${
                    mobileView ? "text-base" : "text-xs md:text-sm"
                  } font-medium`}>
                  {initials.toUpperCase()}
                </span>
              </div>
              {!mobileView && (
                <div className="hidden sm:flex flex-col items-start">
                  <span className="text-xs font-medium leading-none">
                    {userDetails?.name?.en}
                  </span>
                  <span className="text-[10px] text-gray-500 leading-none mt-1">
                    External Organization
                  </span>
                </div>
              )}
              {mobileView && (
                <div className="flex flex-col items-start ml-3">
                  <span className="text-sm font-medium leading-none">
                    {userDetails?.name?.en}
                  </span>
                  <span className="text-xs text-gray-500 leading-none mt-1">
                    External Organization
                  </span>
                </div>
              )}
              <ChevronDown className="h-3 w-3 md:h-4 md:w-4 text-gray-500" />
            </Button>
          </DropdownMenu.Trigger>
          <DropdownMenu.Content
            className={`w-48 p-1 bg-white shadow-xl rounded-md ${
              mobileView ? "ml-4" : ""
            }`}
            align={mobileView ? "start" : "end"}>
            <DropdownMenu.Item
              className="flex items-center px-3 py-2.5 text-sm text-gray-700 hover:bg-primary-100 rounded-md cursor-pointer"
              onClick={() => handleNavigation("/profile")}>
              <User className="mr-2.5 h-4 w-4 text-gray-500" />
              <span>{t("header.viewProfile")}</span>
            </DropdownMenu.Item>
            <DropdownMenu.Item
              className="flex items-center px-3 py-2.5 text-sm text-gray-700 hover:bg-primary-100 rounded-md cursor-pointer"
              onClick={() =>
                handleNavigation("/record-management/change-password")
              }>
              <Key className="mr-2.5 h-4 w-4 text-gray-500" />
              <span>{t("header.changePassword")}</span>
            </DropdownMenu.Item>
            <DropdownMenu.Separator className="my-1 h-px bg-gray-200" />
            <DropdownMenu.Item
              className="flex items-center px-3 py-2.5 text-sm text-red-600 hover:bg-red-50 rounded-md cursor-pointer"
              onClick={handleLogout}>
              <LogOut className="mr-2.5 h-4 w-4" />
              <span>{t("header.signOut")}</span>
            </DropdownMenu.Item>
          </DropdownMenu.Content>
        </DropdownMenu.Root>
      </div>
    </>
  );
};
