'use client';
import { FunctionComponent } from 'react';
import Divider from '@mui/material/Divider';
import Popover from '@mui/material/Popover';
import Skeleton from '@mui/material/Skeleton';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { useTheme } from '@mui/material/styles';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import AppButton from '@/components/common/AppButton';
import { notificationsPath } from '@/constants';
import {
  notificationDeepLink,
  useMarkAllRead,
  useMarkNotificationRead,
  useNotifications,
} from '@/services/notifications';
import type { AppNotification } from '@/services/notifications/types';
import { formatRelativeTime, formatShamsiDate } from '@/utils';
import NotificationRow from './NotificationRow';

/** The 5 most recent — a preview, not the full center (§3.6). */
const POPOVER_RECENT_COUNT = 5;

export interface NotificationBellPopoverProps {
  open: boolean;
  anchorEl: HTMLElement | null;
  onClose: () => void;
  role: 'nurse';
}

/**
 * The nurse-desktop bell's popover preview (§3.6) — the 5 most recent notifications, mark-all-read, and
 * «مشاهده همه» to the full center. Fetches **on open** (`enabled: open`), reusing the same
 * `notificationKeys` cache the full center reads — never on the polled count's tick, and it never reads
 * `useUnreadCount` itself (only the bell container does — §5 isolation).
 * @component NotificationBellPopover
 */
const NotificationBellPopover: FunctionComponent<NotificationBellPopoverProps> = ({ open, anchorEl, onClose, role }) => {
  const t = useTranslations('notifications');
  const locale = useLocale();
  const router = useRouter();
  const theme = useTheme();
  const edge = theme.direction === 'rtl' ? 'left' : 'right';

  const { data, isLoading } = useNotifications(POPOVER_RECENT_COUNT, { enabled: open });
  const markRead = useMarkNotificationRead();
  const markAll = useMarkAllRead();
  const items = data?.items ?? [];
  const hasUnread = items.some((n) => !n.isRead);

  const openNotification = (notification: AppNotification) => {
    if (!notification.isRead) markRead.mutate(notification.id);
    const target = notificationDeepLink(notification, role);
    if (target) {
      router.push(`/${locale}${target}`);
      onClose();
    }
  };

  const viewAll = () => {
    router.push(`/${locale}${notificationsPath(role)}`);
    onClose();
  };

  return (
    <Popover
      open={open}
      anchorEl={anchorEl}
      onClose={onClose}
      anchorOrigin={{ vertical: 'bottom', horizontal: edge }}
      transformOrigin={{ vertical: 'top', horizontal: edge }}
    >
      <Stack sx={{ width: 360, maxWidth: '90vw', p: 1.5, gap: 1.5 }}>
        <Stack direction="row" sx={{ alignItems: 'center', justifyContent: 'space-between' }}>
          <Typography variant="subtitle2" sx={{ fontWeight: 800 }}>
            {t('title')}
          </Typography>
          {hasUnread ? (
            <AppButton variant="text" color="primary" size="small" onClick={() => markAll.mutate()} disabled={markAll.isPending}>
              {t('mark_all_read')}
            </AppButton>
          ) : null}
        </Stack>

        {isLoading ? (
          <Stack sx={{ gap: 1 }}>
            {[0, 1].map((i) => (
              <Skeleton key={i} variant="rounded" height={64} />
            ))}
          </Stack>
        ) : items.length === 0 ? (
          <Typography variant="body2" sx={{ color: 'var(--bal-text-secondary)', textAlign: 'center', py: 2 }}>
            {t('empty_title')}
          </Typography>
        ) : (
          <Stack sx={{ gap: 1 }}>
            {items.map((notification) => {
              const target = notificationDeepLink(notification, role);
              return (
                <NotificationRow
                  key={notification.id}
                  notification={notification}
                  timeLabel={formatRelativeTime(notification.createdAt, locale, formatShamsiDate)}
                  navigable={target != null}
                  onOpen={() => openNotification(notification)}
                />
              );
            })}
          </Stack>
        )}

        <Divider />
        <AppButton variant="text" color="primary" onClick={viewAll} sx={{ alignSelf: 'center' }}>
          {t('view_all')}
        </AppButton>
      </Stack>
    </Popover>
  );
};

export default NotificationBellPopover;
