'use client';
import { FunctionComponent, useState } from 'react';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useTheme } from '@mui/material/styles';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { notificationsPath } from '@/constants';
import { useUnreadCount } from '@/services/notifications';
import NotificationBellPopover from './NotificationBellPopover';
import NotificationBellView from './NotificationBellView';

export interface NotificationBellProps {
  /** The shell the bell lives in — decides which notification center it opens. */
  role: 'customer' | 'nurse' | 'admin';
}

/**
 * The notification bell **container** mounted in the app chrome. It subscribes to the polling
 * `useUnreadCount` (stale-while-revalidate) — the only thing in this component that re-renders on a count
 * change, so the shell around it never does (§5 isolation). On the **nurse desktop** shell (§3.6) it opens
 * a popover preview instead of navigating; every other case (customer — mobile-first, always navigates;
 * nurse mobile; admin) keeps the direct full-page navigation.
 * @component NotificationBell
 */
const NotificationBell: FunctionComponent<NotificationBellProps> = ({ role }) => {
  const count = useUnreadCount();
  const router = useRouter();
  const locale = useLocale();
  const t = useTranslations('notifications');
  const theme = useTheme();
  const isDesktop = useMediaQuery(theme.breakpoints.up('md'));
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const [popoverOpen, setPopoverOpen] = useState(false);

  const usesPopover = role === 'nurse' && isDesktop;

  const onClick = () => {
    if (usesPopover) {
      setPopoverOpen(true);
      return;
    }
    router.push(`/${locale}${notificationsPath(role)}`);
  };

  return (
    <>
      <NotificationBellView ref={setAnchorEl} count={count} label={t('bell_aria', { count })} onClick={onClick} />
      {usesPopover ? (
        <NotificationBellPopover
          open={popoverOpen}
          anchorEl={anchorEl}
          onClose={() => setPopoverOpen(false)}
          role="nurse"
        />
      ) : null}
    </>
  );
};

export default NotificationBell;
