import React from 'react';
import styled from 'styled-components';
import { Link, useNavigate } from 'react-router-dom';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Button, Spinner } from '@/shared/components/ui';
import { ROUTES } from '@/shared/constants/routes';
import { NotificationListItem } from '@/features/notifications/components/NotificationListItem';
import { useNotifications } from '@/features/notifications/hooks/useNotifications';
import { useNotificationMutations } from '@/features/notifications/hooks/useNotificationMutations';
import { getNotificationTicketId, type NotificationItem } from '@/features/notifications/types/notification.types';

const Panel = styled.div`
  position: absolute;
  top: calc(100% + 8px);
  inset-inline-end: 0;
  width: min(400px, calc(100vw - 24px));
  max-height: 480px;
  background-color: ${({ theme }) => theme.colors.surfaceElevated};
  border: 1px solid ${({ theme }) => theme.colors.border};
  border-radius: ${({ theme }) => theme.borderRadius.xl};
  box-shadow: ${({ theme }) => theme.shadows.lg};
  z-index: ${({ theme }) => theme.zIndex.dropdown};
  display: flex;
  flex-direction: column;
  overflow: hidden;
`;

const PanelHeader = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: ${({ theme }) => `${theme.spacing[4]} ${theme.spacing[5]}`};
  border-bottom: 1px solid ${({ theme }) => theme.colors.divider};
  background-color: ${({ theme }) => theme.colors.surfaceMuted};
`;

const PanelTitle = styled.h2`
  margin: 0;
  font-size: ${({ theme }) => theme.typography.fontSize.base};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  text-align: start;
`;

const List = styled.div`
  overflow-y: auto;
  flex: 1;
  padding: ${({ theme }) => theme.spacing[2]};
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[2]};
`;

const Centered = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: ${({ theme }) => theme.spacing[2]};
  padding: ${({ theme }) => theme.spacing[8]} ${({ theme }) => theme.spacing[4]};
  color: ${({ theme }) => theme.colors.text.secondary};
  text-align: center;
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
`;

const PanelFooter = styled.div`
  padding: ${({ theme }) => theme.spacing[3]} ${({ theme }) => theme.spacing[4]};
  border-top: 1px solid ${({ theme }) => theme.colors.border};
  display: flex;
  justify-content: space-between;
  gap: ${({ theme }) => theme.spacing[2]};
`;

interface NotificationDropdownProps {
  onClose: () => void;
}

export const NotificationDropdown: React.FC<NotificationDropdownProps> = ({ onClose }) => {
  const { t } = useLocale();
  const navigate = useNavigate();
  const notificationsQuery = useNotifications({ per_page: 8, page: 1 });
  const { markReadMutation, markAllReadMutation, deleteMutation } = useNotificationMutations();

  const handleOpenTicket = (notification: NotificationItem, ticketId: string) => {
    if (!notification.is_read) {
      void markReadMutation.mutateAsync(notification.id).catch(() => undefined);
    }
    onClose();
    navigate(ROUTES.TICKET_DETAIL(ticketId));
  };

  return (
    <Panel role="dialog" aria-label={t('notifications:dropdown.title')}>
      <PanelHeader>
        <PanelTitle>{t('notifications:dropdown.title')}</PanelTitle>
        <Button
          type="button"
          variant="ghost"
          size="sm"
          loading={markAllReadMutation.isPending}
          onClick={() => markAllReadMutation.mutate()}
        >
          {t('notifications:actions.markAllRead')}
        </Button>
      </PanelHeader>

      {notificationsQuery.isLoading ? (
        <Centered role="status">
          <Spinner />
          <span>{t('notifications:states.loading')}</span>
        </Centered>
      ) : notificationsQuery.isError ? (
        <Centered role="alert">
          <span>{t('notifications:states.error')}</span>
          <Button variant="outline" size="sm" onClick={() => notificationsQuery.refetch()}>
            {t('notifications:states.retry')}
          </Button>
        </Centered>
      ) : (notificationsQuery.data?.items.length ?? 0) === 0 ? (
        <Centered>
          <span>{t('notifications:states.empty')}</span>
        </Centered>
      ) : (
        <List>
          {notificationsQuery.data?.items.map((notification) => {
            const ticketId = getNotificationTicketId(notification);
            return (
              <NotificationListItem
                key={notification.id}
                notification={notification}
                compact
                showTicketLink={Boolean(ticketId)}
                onOpenTicket={
                  ticketId
                    ? () => handleOpenTicket(notification, ticketId)
                    : undefined
                }
                onMarkRead={(id) => markReadMutation.mutate(id)}
                onDelete={(id) => deleteMutation.mutate(id)}
                isMarkingRead={markReadMutation.isPending}
                isDeleting={deleteMutation.isPending}
              />
            );
          })}
        </List>
      )}

      <PanelFooter>
        <Link to={ROUTES.NOTIFICATION_PREFERENCES} onClick={onClose}>
          <Button type="button" variant="ghost" size="sm">
            {t('notifications:actions.preferences')}
          </Button>
        </Link>
        <Link to={ROUTES.NOTIFICATIONS} onClick={onClose}>
          <Button type="button" variant="primary" size="sm">
            {t('common:actions.viewAll')}
          </Button>
        </Link>
      </PanelFooter>
    </Panel>
  );
};
