import { useAuth } from '@/client/mobile/hooks/AuthProvider';
import { useEffect, useState, useCallback } from 'react';
import { io, Socket } from 'socket.io-client';

interface ExamData {
  roomId: string;
  question: {
    date: string;
    price: number;
    gain?: number;
  };
}

interface StockSocketClient {
  // connect(): void;
  // disconnect(): void;
  pushExamData(data: { roomId: string; question: { date: string; price: number; gain?: number } }): void;
  error: Error | null;
  isConnected: boolean;
}

export function useStockSocket(classRoom: string | null): StockSocketClient {
  const { token } = useAuth();
  const [socket, setSocket] = useState<Socket | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const [isConnected, setIsConnected] = useState(false);

  // 初始化socket连接
  useEffect(() => {
    if (!token || !classRoom) return;

    const newSocket = io('/', {
      path: '/socket.io',
      transports: ['websocket'],
      withCredentials: true,
      query: { 
        socket_token:token
      },
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
    });

    newSocket.on('connect', () => {
      console.log('Exam socket connected');
      setIsConnected(true);
    });

    newSocket.on('disconnect', () => {
      console.log('Exam socket disconnected');
      setIsConnected(false);
    });

    newSocket.on('error', (err) => {
      console.error('Exam socket error:', err);
      setError(err);
    });

    setSocket(newSocket);

    return () => {
      newSocket.disconnect();
    };
  }, [token]);

  // const connect = useCallback(() => {
  //   if (socket && !socket.connected) {
  //     socket.connect();
  //   }
  // }, [socket]);

  // const disconnect = useCallback(() => {
  //   if (socket && socket.connected) {
  //     socket.disconnect();
  //   }
  // }, [socket]);

  const pushExamData = useCallback((data: ExamData) => {
    if (socket) {
      socket.emit('exam:question', {
        roomId: data.roomId,
        question: {
          date: data.question.date,
          price: data.question.price,
          gain: data.question.gain
        }
      });
    }
  }, [socket]);

  return {
    // connect,
    // disconnect,
    pushExamData,
    error,
    isConnected,
  };
}