import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { HiBell } from 'react-icons/hi';
import { useLocale } from '@/app/providers/LocaleProvider';
import { IconButton } from '@/shared/components/ui/IconButton/IconButton';
import { useUnreadCount } from '@/features/notifications/hooks/useUnreadCount';
import { NotificationDropdown } from '@/features/notifications/components/NotificationDropdown';

const BellWrapper = styled.div`
  position: relative;
  display: inline-flex;
`;

const CountBadge = styled.span`
  position: absolute;
  top: 4px;
  inset-inline-end: 4px;
  min-width: 18px;
  height: 18px;
  padding: 0 5px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  background-color: ${({ theme }) => theme.colors.error};
  color: ${({ theme }) => theme.colors.text.inverse};
  font-size: 0.625rem;
  font-weight: ${({ theme }) => theme.typography.fontWeight.bold};
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
  pointer-events: none;
  box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.surface};
`;

export const NotificationBell: React.FC = () => {
  const { t } = useLocale();
  const [isOpen, setIsOpen] = useState(false);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const unreadQuery = useUnreadCount();

  const unreadCount = unreadQuery.data ?? 0;
  const displayCount = unreadCount > 99 ? '99+' : String(unreadCount);

  useEffect(() => {
    if (!isOpen) {
      return undefined;
    }

    const handlePointerDown = (event: MouseEvent) => {
      if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handlePointerDown);
    return () => document.removeEventListener('mousedown', handlePointerDown);
  }, [isOpen]);

  return (
    <BellWrapper ref={wrapperRef} data-testid="notification-bell">
      <IconButton
        label={t('common:navigation.notifications')}
        aria-expanded={isOpen}
        aria-haspopup="dialog"
        onClick={() => setIsOpen((open) => !open)}
      >
        <HiBell aria-hidden />
      </IconButton>
      {unreadCount > 0 && (
        <CountBadge aria-label={t('notifications:labels.unreadCount', { count: unreadCount })}>
          {displayCount}
        </CountBadge>
      )}
      {isOpen && <NotificationDropdown onClose={() => setIsOpen(false)} />}
    </BellWrapper>
  );
};
