import React, { useEffect, useState, useCallback } from "react";
import { useNavigate, useLocation } from "react-router";
import Logo from "../assets/logo.png";
import { Axiosinstance } from "../services/auth/Axiosinstance";
import { useAuthStore } from "../store/authstore";
import { useToast } from "../components/ToastProvider";

import NotificationsMenu from "./navbar/NotificationsMenu";
import AccountMenu from "./navbar/AccountMenu";
import ThemeToggle from "./navbar/ThemeToggle";

export default function Navbar() {
  const navigate = useNavigate();
  const location = useLocation();
  const { refreshToken, clearTokens } = useAuthStore();
  const { error: toastError, success, info } = useToast();

  const [theme, setTheme] = useState(() => {
    if (typeof window === "undefined") return "light";
    return localStorage.getItem("theme") || "light";
  });

  // ✅ theme sync
  useEffect(() => {
    if (theme === "dark") {
      document.documentElement.classList.add("dark");
      localStorage.setItem("theme", "dark");
    } else {
      document.documentElement.classList.remove("dark");
      localStorage.setItem("theme", "light");
    }
  }, [theme]);

  const logout = useCallback(async () => {
    try {
      await Axiosinstance.post("accounts/logout/", { refresh: refreshToken });
    } catch (error) {
      toastError(
        error?.response?.data?.detail ||
          error?.response?.data?.message ||
          "خروج با خطا مواجه شد.",
        { title: "خطا" }
      );
    } finally {
      clearTokens();
      navigate("/auth/login");
    }
  }, [refreshToken, clearTokens, navigate, toastError]);

  // ✅ برای اینکه وقتی یکی باز شد، اون یکی بسته شه:
  // ساده‌ترین راه: NotificationsMenu و AccountMenu هرکدوم onOpen می‌گیرن که دیگری رو ببنده
  // ما اینجا فقط “سیگنال” می‌دیم.
  const [closeSignal, setCloseSignal] = useState(0);
  const closeOtherMenus = () => setCloseSignal((x) => x + 1);

  return (
    <div className="w-full fixed xl:relative dark:bg-[#001F3F] bg-[#f2f2f2] z-50 flex justify-between items-center h-fit xl:p-5 p-2 pb-0">
      <div className="flex items-center dark:text-white">
        <img src={Logo} alt="logo" className="h-20 object-contain" />
      </div>

      <div className="flex gap-4 bg-white dark:bg-[#16325b] p-4 rounded-4xl items-center">
        <NotificationsMenu
          // وقتی نوتیف باز شد، اکانت بسته شه (با closeSignal داخلی)
          onOpen={closeOtherMenus}
          navigate={navigate}
          Axiosinstance={Axiosinstance}
          toastError={toastError}
          successToast={success}
          closeSignal={closeSignal}
        />

        <div className="mx-1 w-px h-6 bg-[#43BEFF80] dark:bg-white/10" />

        <AccountMenu
          activePath={location.pathname}
          onOpen={closeOtherMenus}
          navigate={navigate}
          logout={logout}
          closeSignal={closeSignal}
        />

        <div className="mx-1 w-px h-6 bg-[#43BEFF80] dark:bg-white/10" />

        <ThemeToggle
          theme={theme}
          setTheme={setTheme}
          onInfo={(msg) => info(msg, { title: "تم" })}
        />
      </div>
    </div>
  );
}
