import { useEffect, useState, useCallback } from 'react';
import { PriceIndex, HistoricalData } from '../../shared/types';

interface WebSocketStatus {
  connected: boolean;
  state: string;
  error?: string;
}

export function useWebSocket() {
  const [status, setStatus] = useState<WebSocketStatus>({
    connected: false,
    state: 'DISCONNECTED',
  });
  const [latestPrice, setLatestPrice] = useState<PriceIndex | null>(null);
  const [historyData, setHistoryData] = useState<HistoricalData | null>(null);

  useEffect(() => {
    // Listen for WebSocket events from main process
    const handleConnected = () => {
      setStatus({ connected: true, state: 'CONNECTED' });
    };

    const handleDisconnected = () => {
      setStatus({ connected: false, state: 'DISCONNECTED' });
    };

    const handlePriceUpdate = (data: PriceIndex) => {
      setLatestPrice(data);
    };

    const handleHistoryData = (data: HistoricalData) => {
      setHistoryData(data);
    };

    const handleError = (error: string) => {
      setStatus((prev: WebSocketStatus) => ({ ...prev, error }));
    };

    const handleMaxReconnect = () => {
      setStatus((prev: WebSocketStatus) => ({ 
        ...prev, 
        error: 'Maximum reconnection attempts reached. Please restart the application.' 
      }));
    };

    // Register IPC listeners
    window.electron.ipcRenderer.on('ws:connected', handleConnected);
    window.electron.ipcRenderer.on('ws:disconnected', handleDisconnected);
    window.electron.ipcRenderer.on('ws:priceUpdate', handlePriceUpdate);
    window.electron.ipcRenderer.on('ws:historyData', handleHistoryData);
    window.electron.ipcRenderer.on('ws:error', handleError);
    window.electron.ipcRenderer.on('ws:maxReconnectAttemptsReached', handleMaxReconnect);

    // Get initial status
    window.electron.ipcRenderer.invoke('ws:getStatus').then((initialStatus) => {
      setStatus(initialStatus);
    });

    // Cleanup
    return () => {
      window.electron.ipcRenderer.removeAllListeners('ws:connected');
      window.electron.ipcRenderer.removeAllListeners('ws:disconnected');
      window.electron.ipcRenderer.removeAllListeners('ws:priceUpdate');
      window.electron.ipcRenderer.removeAllListeners('ws:historyData');
      window.electron.ipcRenderer.removeAllListeners('ws:error');
      window.electron.ipcRenderer.removeAllListeners('ws:maxReconnectAttemptsReached');
    };
  }, []);

  const connect = useCallback(async () => {
    await window.electron.ipcRenderer.invoke('ws:connect');
  }, []);

  const disconnect = useCallback(async () => {
    await window.electron.ipcRenderer.invoke('ws:disconnect');
  }, []);

  const sendMessage = useCallback(async (message: any) => {
    await window.electron.ipcRenderer.invoke('ws:send', message);
  }, []);

  const requestHistory = useCallback(async (range: string) => {
    await sendMessage({ type: 'get_history', data: { range } });
  }, [sendMessage]);

  const fetchInitialData = useCallback(async () => {
    try {
      const response = await window.electron.ipcRenderer.invoke('api:getLatestPrices');
      if (response.success && response.data) {
        setLatestPrice(response.data);
      }
    } catch (error) {
      console.error('Failed to fetch initial data:', error);
    }
  }, []);

  return {
    status,
    latestPrice,
    historyData,
    connect,
    disconnect,
    sendMessage,
    requestHistory,
    fetchInitialData,
  };
}
