import { useCallback, useEffect, useRef } from 'react';
import { type ChatMessage } from '../api';
import { useAuth } from '../auth/AuthContext';
import { playChatSound } from '../utils/notifySound';

type ChatIncomingHandler = (msg: ChatMessage) => void;

const handlers = new Set<ChatIncomingHandler>();

export function onStaffChatMessage(handler: ChatIncomingHandler): () => void {
  handlers.add(handler);
  return () => { handlers.delete(handler); };
}

/** WebSocket luôn bật khi đã login — nhận tin sinh viên realtime */
export function StaffChatSocket() {
  const { staff, token } = useAuth();
  const staffIdRef = useRef(0);

  useEffect(() => {
    staffIdRef.current = staff?.id ?? 0;
  }, [staff?.id]);

  const dispatch = useCallback((msg: ChatMessage) => {
    handlers.forEach((h) => h(msg));
  }, []);

  useEffect(() => {
    if (!token || !staff?.id) return;

    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.hostname}:8080/ws?role=teacher&staffId=${staff.id}`;
    let ws: WebSocket | null = null;
    let retryTimer: ReturnType<typeof setTimeout> | null = null;
    let closed = false;

    const connect = () => {
      if (closed) return;
      ws = new WebSocket(wsUrl);
      ws.onmessage = (ev) => {
        try {
          const payload = JSON.parse(ev.data);
          if (payload.event !== 'chat:message') return;
          const msg = payload.data as ChatMessage;
          const targetStaff = Number(msg.targetStaffId ?? msg.staffId ?? 0);
          if (targetStaff > 0 && targetStaff !== staffIdRef.current) return;
          dispatch(msg);
        } catch {
          /* ignore */
        }
      };
      ws.onclose = () => {
        if (!closed) {
          retryTimer = setTimeout(connect, 3000);
        }
      };
    };

    connect();

    return () => {
      closed = true;
      if (retryTimer) clearTimeout(retryTimer);
      ws?.close();
    };
  }, [token, staff?.id, dispatch]);

  return null;
}

export { playChatSound };
