import { useState, useEffect, useRef, useCallback } from 'react';
import { useAuthStore } from '@/stores/auth.store';

export interface ChatNotification {
  id: string; // generated client-side
  type: 'chat_reply';
  videoId: number;
  videoTitle: string;
  commentId: number;
  commenterName: string;
  contentPreview: string;
  receivedAt: number;
}

export function useChatNotifications() {
  const { accessToken, isAuthenticated } = useAuthStore();
  const [notifications, setNotifications] = useState<ChatNotification[]>([]);
  const eventSourceRef = useRef<EventSource | null>(null);
  const notifCounterRef = useRef(0);

  const clearNotification = useCallback((id: string) => {
    setNotifications((prev) => prev.filter((n) => n.id !== id));
  }, []);

  const clearAll = useCallback(() => {
    setNotifications([]);
  }, []);

  useEffect(() => {
    if (!isAuthenticated || !accessToken) {
      if (eventSourceRef.current) {
        eventSourceRef.current.close();
        eventSourceRef.current = null;
      }
      return;
    }

    // Use relative URL through nginx proxy
    const url = `/media/media/notifications/stream?token=${encodeURIComponent(accessToken)}`;
    const es = new EventSource(url);

    es.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);

        if (data.type === 'connected') return;

        if (data.type === 'chat_reply') {
          const notif: ChatNotification = {
            ...data,
            id: `notif-${++notifCounterRef.current}-${Date.now()}`,
            receivedAt: Date.now(),
          };

          setNotifications((prev) => {
            // Keep max 10 notifications
            const updated = [...prev, notif];
            return updated.slice(-10);
          });
        }
      } catch {
        // Ignore parse errors
      }
    };

    es.onerror = () => {
      // Auto-reconnect is handled by EventSource
    };

    eventSourceRef.current = es;

    return () => {
      es.close();
      eventSourceRef.current = null;
    };
  }, [isAuthenticated, accessToken]);

  return { notifications, clearNotification, clearAll };
}
