"use client";

import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { useNotificationStore } from "@/store/notificationStore";
import { getDefaultProfileImage } from "@/lib/helpers";
import { revokeSessionTokens } from "@/lib/api/revokeSession";
import { useQuery } from "@tanstack/react-query";
import { getAccountInfo } from "@/features/profile/services/profileApi";

/**
 * The header's state: which nav items this visitor sees, the mobile menu and
 * dropdowns, and sign-out.
 *
 * The nav lists depend on `user_type`, so they are derived here rather than
 * being constants.
 */
export function useHeader() {
  const pathname = usePathname();
  const router = useRouter();
  const [menuOpen, setMenuOpen] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState<string | null>(null);

  const user = useAuthStore((s) => s.user);
  /* BE-129 — the other sessions this device holds, which is what decides
     whether signing out is one account or all of them. */
  const accounts = useAuthStore((s) => s.accounts);
  const signOutActiveAccount = useAuthStore((s) => s.signOutActiveAccount);
  const logout = useAuthStore((s) => s.logout);
  const language = useLanguageStore((s) => s.language);
  const unreadCount = useNotificationStore((s) => s.unreadCount);

  const isLoggedIn = !!user;
  const isVolunteer =
    isLoggedIn &&
    (user?.user_type === "individual" || user?.user_type === "volunteer");
  const isOrganizer = isLoggedIn && user?.user_type === "organization";

  /*
   * The gender behind the default avatar.
   *
   * `gender_display` is **not** in the sign-in payload, so a stored user has
   * no gender until something fills it in — which is why the header drew every
   * volunteer as the grey organization mark while `/volunteer-profile`, which
   * fetches its own data, drew them correctly.
   *
   * `/account/` does carry it, under the `["account-info"]` key four other
   * screens already use, so on any page that has shown a profile this is a
   * cache read rather than a request.
   *
   * The fetched value is read **first** and the stored one is only the
   * fallback. The other way round — store first, write the fetch back, re-read
   * — makes the avatar depend on a round trip through `updateUser` landing
   * before the next render, and leaves it grey for the whole session if that
   * write is ever skipped. Reading the response directly is one render, no
   * ordering to get wrong.
   */
  const { data: accountInfo } = useQuery({
    queryKey: ["account-info"],
    queryFn: getAccountInfo,
    enabled: isLoggedIn,
  });
  const fetchedGender = accountInfo?.data?.gender_display ?? null;
  const genderEn =
    fetchedGender?.value_en ?? user?.gender_display?.value_en ?? undefined;

  /*
   * The write-back exists for the account switcher, not for the avatar above.
   * Those rows are drawn from stored sessions — a backgrounded account cannot
   * be fetched, since the request would need its token — so the only way its
   * row ever shows the right silhouette is for the gender to be saved while
   * that account is the active one.
   */
  useEffect(() => {
    if (fetchedGender && !useAuthStore.getState().user?.gender_display) {
      useAuthStore.getState().updateUser({ gender_display: fetchedGender });
    }
  }, [fetchedGender]);

  /*
   * The silhouette shown when the account has no picture of its own.
   *
   * Same four-argument shape every other avatar in the app uses
   * (`RegistrationNameCell`, `AvailableVolunteersList`, the pickers). An
   * organization has no `gender_display` at all — it hangs off the volunteer
   * profile — so the fourth argument serves it without a branch.
   */
  const defaultProfilePic = getDefaultProfileImage(
    genderEn,
    "/assets/profile/male_profile.svg",
    "/assets/profile/female_profile.svg",
    "/assets/profile/org_profile.svg"
  );

  const profilePicUrl = user?.profile_pic || defaultProfilePic;

  const hasOtherAccounts = accounts.length > 0;

  /*
   * BE-129 — signing out of **this** account.
   *
   * With another session stored, the reader continues as it rather than being
   * put on the street: pressing sign-out on one of two accounts means "I am
   * done being this person", not "forget my other login too". A full reload
   * rather than a router push, for the same reason a switch reloads — every
   * cached query on the page was answered for the account that just ended.
   *
   * The final account uses the same fresh-document navigation, so the login
   * route never inherits the previous session's mounted router/query tree.
   */
  const handleLogout = () => {
    setMenuOpen(false);
    setDropdownOpen(null);
    revokeSessionTokens([useAuthStore.getState().user?.auth_token]);
    signOutActiveAccount();
    // Always start a fresh document, including when the last account ends.
    // The query provider changes account scope, so a client router transition
    // here would be scheduled from the tree being unmounted.
    window.location.assign("/");
  };

  /** Every session on this device — offered only when there is more than one. */
  const handleLogoutAll = () => {
    setMenuOpen(false);
    setDropdownOpen(null);
    const { user, accounts } = useAuthStore.getState();
    revokeSessionTokens([user?.auth_token, ...accounts.map((account) => account.auth_token)]);
    logout();
    window.location.assign("/");
  };

  useEffect(() => {
    if (menuOpen) {
      document.body.classList.add("body-no-scroll");
    } else {
      document.body.classList.remove("body-no-scroll");
    }
    return () => {
      document.body.classList.remove("body-no-scroll");
    };
  }, [menuOpen]);

  /*
   * Close the mobile menu and any dropdown on route change — including a
   * change the header did not cause, such as the back button, which is why
   * this is not done in the link handlers.
   *
   * React's adjust-on-change pattern rather than an effect: the effect
   * committed one frame with the new page *behind the still-open overlay* and
   * with `body-no-scroll` still applied, then re-rendered. Resetting during
   * the render that observes the new pathname means that frame never paints.
   */
  const [renderedPathname, setRenderedPathname] = useState(pathname);
  if (pathname !== renderedPathname) {
    setRenderedPathname(pathname);
    setMenuOpen(false);
    setDropdownOpen(null);
  }

  const close = () => {
    setMenuOpen(false);
    setDropdownOpen(null);
  };

  return {
    pathname,
    router,
    menuOpen,
    setMenuOpen,
    dropdownOpen,
    setDropdownOpen,
    user,
    logout,
    language,
    unreadCount,
    isLoggedIn,
    isVolunteer,
    isOrganizer,
    profilePicUrl,
    defaultProfilePic,
    handleLogout,
    handleLogoutAll,
    hasOtherAccounts,
    close,
  };
}
