"use client";

import Image from "next/image";
import Link from "next/link";
import { Suspense, useEffect, useRef, useState, useSyncExternalStore } from "react";
import { useClickOutside } from "@/hooks/useClickOutside";
import { ChevronDownIcon } from "./icons";
import NotificationMenu from "./NotificationMenu";
import TopbarBreadcrumb from "./TopbarBreadcrumb";
import { useAppDispatch, useAppSelector } from "@/state/hooks";
import { logoutAdmin } from "@/state/auth";
import { fetchNotifications } from "@/state/notification/notificationSlice";
import { clearAuthCookie } from "@/lib/cookies";
import { fetchProfile } from "@/state/profile/profileSlice";
import { getImageUrl } from "@/lib/imageUrl";
import AvatarImage from "../common/AvatarImage";

const emptySubscribe = () => () => {};
function useIsMounted() {
  return useSyncExternalStore(
    emptySubscribe,
    () => true,
    () => false
  );
}

function getInitials(name?: string, email?: string): string {
  if (name && name.trim()) {
    const parts = name.trim().split(/\s+/);
    if (parts.length >= 2) {
      return (parts[0][0] + parts[1][0]).toUpperCase();
    }
    return name.slice(0, 2).toUpperCase();
  }
  if (email && email.length >= 2) {
    return email.slice(0, 2).toUpperCase();
  }
  return "";
}

export default function Topbar() {
  const dispatch = useAppDispatch();
  const user = useAppSelector((state) => state.auth.user);
  const profile = useAppSelector((state) => state.profile.profile);
  const unreadCount = useAppSelector((state) => state.notification.unreadCount);
  const mounted = useIsMounted();

  const currentUser = mounted ? (profile || user) : null;

  const [menuOpen, setMenuOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement | null>(null);

  useClickOutside(menuRef, () => setMenuOpen(false));

  useEffect(() => {
    dispatch(fetchNotifications());
    if (!profile) {
      dispatch(fetchProfile());
    }
  }, [dispatch, profile]);

  const displayName = mounted
    ? currentUser?.name ||
      (currentUser?.firstName ? `${currentUser.firstName} ${currentUser.lastName || ""}`.trim() : "") ||
      ""
    : "";
  const displayEmail = mounted ? currentUser?.email || "" : "";
  const initials = mounted ? getInitials(displayName, displayEmail) : "";
  const avatarUrl = mounted && (currentUser?.profileImage || currentUser?.avatar)
    ? getImageUrl(currentUser.profileImage || currentUser.avatar)
    : null;

  const handleLogout = () => {
    setMenuOpen(false);
    // 1. Wipe the auth cookie — middleware will block all protected pages immediately
    clearAuthCookie();
    localStorage.removeItem("auth");
    sessionStorage.removeItem("auth");
    // 2. Fire backend logout in background (non-blocking)
    dispatch(logoutAdmin());
    // 3. Replace current history entry so Back button can't return to dashboard
    window.location.replace("/login");
  };

  return (
    <header className="flex w-full items-center justify-between bg-white px-6 py-5">
      <Suspense fallback={<p className="text-[13px] font-medium text-[#344054]">&nbsp;</p>}>
        <TopbarBreadcrumb />
      </Suspense>

      <div className="flex items-center gap-4">
        <div className="relative">
          <button
            type="button"
            onClick={() => setNotifOpen((prev) => !prev)}
            className="relative flex h-10 w-10 items-center justify-center rounded-lg border border-[#E4E7EC] text-[#475467] transition-colors hover:bg-[#F5F7F9] cursor-pointer"
            aria-label="Notifications"
          >
            <Image src="/assets/notification-bell.png" alt="" width={18} height={20} />
            {unreadCount > 0 && (
              <span className="absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-[#DC2626] px-1 text-[10px] font-bold text-white">
                {unreadCount > 99 ? "99+" : unreadCount}
              </span>
            )}
          </button>
          <NotificationMenu open={notifOpen} onClose={() => setNotifOpen(false)} />
        </div>

        <div className="h-8 w-px bg-[#E4E7EC]" />

        <div ref={menuRef} className="relative">
          <button
            type="button"
            onClick={() => setMenuOpen((prev) => !prev)}
            className="flex items-center gap-2.5 cursor-pointer"
          >
            <div className="flex h-10 w-10 items-center justify-center overflow-hidden rounded-full bg-[#1657D9] text-[13px] font-semibold text-white">
              <AvatarImage
                src={currentUser?.profileImage || currentUser?.avatar}
                alt={displayName}
                initials={initials}
              />
            </div>
            <div className="text-left leading-tight">
              <div className="flex items-center gap-1.5">
                <span className="text-[13px] font-medium text-[#101828]">
                  {displayName}
                </span>
                <ChevronDownIcon
                  className={`text-[#98A2B3] transition-transform ${
                    menuOpen ? "rotate-180" : ""
                  }`}
                />
              </div>
              <p className="text-[12px] text-[#667085]">{displayEmail}</p>
            </div>
          </button>

          {menuOpen && (
            <div className="absolute right-0 top-[calc(100%+10px)] z-50 min-w-[170px] overflow-hidden rounded-lg border border-[#E4E7EC] bg-white py-1.5 shadow-[0_10px_24px_rgba(15,23,42,0.12)]">
              <Link
                href="/profile"
                onClick={() => setMenuOpen(false)}
                className="flex items-center gap-2.5 px-3.5 py-2 text-[13px] text-[#344054] transition-colors hover:bg-[#F5F7F9]"
              >
                My Profile
              </Link>
              <button
                type="button"
                onClick={handleLogout}
                className="flex w-full items-center gap-2.5 px-3.5 py-2 text-left text-[13px] text-[#344054] transition-colors hover:bg-[#F5F7F9] cursor-pointer"
              >
                Log out
              </button>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
