import { useRef, useState, useEffect, useCallback } from 'react';

import { CONFIG } from 'src/config-global';

// ----------------------------------------------------------------------

export function useChatWebSocket({ chatUuid, enabled = true, onMessage }) {
  const [isConnected, setIsConnected] = useState(false);
  const wsRef = useRef(null);
  const onMessageRef = useRef(onMessage);
  onMessageRef.current = onMessage;

  const disconnect = useCallback(() => {
    if (wsRef.current) {
      wsRef.current.close();
      wsRef.current = null;
    }
    setIsConnected(false);
  }, []);

  const connect = useCallback(() => {
    if (!enabled || !chatUuid) return;
    const token =
      typeof window !== 'undefined'
        ? localStorage.getItem('jwt_access_token') || localStorage.getItem('access_token') || ''
        : '';
    if (!token) return;

    const serverUrl = CONFIG.site.serverUrl || '';
    let apiBase = serverUrl.replace(/\/api\/?$/, '').replace(/\/$/, '');
    if (!apiBase) apiBase = typeof window !== 'undefined' ? window.location.origin : '';

    const wsProtocol = apiBase.startsWith('https') ? 'wss:' : 'ws:';
    const wsHost = apiBase.replace(/^https?:\/\//, '');
    const wsUrl = `${wsProtocol}//${wsHost}/ws/chat/${chatUuid}/?token=${token}`;

    const ws = new WebSocket(wsUrl);
    wsRef.current = ws;

    ws.onopen = () => setIsConnected(true);
    ws.onclose = () => setIsConnected(false);
    ws.onerror = () => setIsConnected(false);
    ws.onmessage = (ev) => {
      try {
        const data = JSON.parse(ev.data);
        if (data.type === 'chat_message' && data.message) {
          onMessageRef.current?.(data.message);
        }
      } catch (_e) {
        // ignore parse errors
      }
    };
  }, [chatUuid, enabled]);

  useEffect(() => {
    disconnect();
    connect();
    return () => disconnect();
  }, [connect, disconnect]);

  return { isConnected };
}
