import { useEffect, useRef } from 'react';
import { notification, Button, Space, Typography } from 'antd';
import { MessageOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ChatNotification } from '@/hooks/useChatNotifications';

const { Text } = Typography;

interface ChatNotificationToastProps {
  notifications: ChatNotification[];
  clearNotification: (id: string) => void;
}

export default function ChatNotificationToast({
  notifications,
  clearNotification,
}: ChatNotificationToastProps) {
  const [api, contextHolder] = notification.useNotification();
  const navigate = useNavigate();
  const shownRef = useRef<Set<string>>(new Set());

  useEffect(() => {
    for (const notif of notifications) {
      if (shownRef.current.has(notif.id)) continue;
      shownRef.current.add(notif.id);

      api.info({
        key: notif.id,
        message: (
          <Space size={4}>
            <MessageOutlined />
            <Text strong>{notif.commenterName}</Text>
            <Text type="secondary">replied</Text>
          </Space>
        ),
        description: (
          <div>
            <Text type="secondary" style={{ fontSize: 12 }}>
              on {notif.videoTitle}
            </Text>
            <div style={{ marginTop: 4 }}>
              <Text style={{ fontSize: 13 }}>{notif.contentPreview}</Text>
            </div>
          </div>
        ),
        placement: 'bottomRight',
        duration: 8,
        btn: (
          <Button
            type="primary"
            size="small"
            onClick={() => {
              navigate(`/gallery/watch/${notif.videoId}`);
              api.destroy(notif.id);
              clearNotification(notif.id);
            }}
          >
            View
          </Button>
        ),
        onClose: () => {
          clearNotification(notif.id);
        },
      });
    }
  }, [notifications, api, clearNotification, navigate]);

  // Cleanup shown IDs when notifications are cleared
  useEffect(() => {
    const currentIds = new Set(notifications.map((n) => n.id));
    for (const id of shownRef.current) {
      if (!currentIds.has(id)) {
        shownRef.current.delete(id);
      }
    }
  }, [notifications]);

  return <>{contextHolder}</>;
}
