import { useState } from 'react';

import {
  countUnreadTopBarNotifications,
  getTopBarCampusLabel,
  getTopBarInitials,
  getTopBarRoleLabel,
} from '@/business/top-bar/selectors';
import type {
  TopBarNotification,
  TopBarPage,
  UseTopBarPageOptions,
} from '@/business/top-bar/types';

const EMPTY_TOP_BAR_NOTIFICATIONS: readonly TopBarNotification[] = [];

export function useTopBarPage({
  userRole,
  userName,
  campusInfo,
  toggleSidebar,
  profile,
  signOut: signOutAction,
}: UseTopBarPageOptions): TopBarPage {
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  const [showNotifications, setShowNotifications] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [signOutError, setSignOutError] = useState<string | null>(null);
  const notifications = EMPTY_TOP_BAR_NOTIFICATIONS;

  async function signOut() {
    setShowProfileMenu(false);
    setSignOutError(null);
    const result = await signOutAction();

    if (result.error) {
      setSignOutError(result.error);
    }
  }

  return {
    userRole,
    userName,
    campusInfo,
    profileRoleLabel: profile ? getTopBarRoleLabel(profile.role) : getTopBarRoleLabel(userRole),
    roleLabel: getTopBarRoleLabel(userRole),
    initials: getTopBarInitials(userName),
    campusLabel: getTopBarCampusLabel(campusInfo),
    showProfileMenu,
    showNotifications,
    searchQuery,
    signOutError,
    notifications,
    unreadCount: countUnreadTopBarNotifications(notifications),
    toggleSidebar,
    toggleProfileMenu: () => setShowProfileMenu((current) => !current),
    closeProfileMenu: () => setShowProfileMenu(false),
    toggleNotifications: () => setShowNotifications((current) => !current),
    closeNotifications: () => setShowNotifications(false),
    setSearchQuery,
    signOut,
  };
}
