import React, { createContext, useContext, useEffect, useState } from 'react';
import { io } from 'socket.io-client';
import { useAuth } from './AuthContext';

const SocketContext = createContext(null);

export const useSocket = () => {
  const context = useContext(SocketContext);
  if (!context) {
    throw new Error('useSocket must be used within a SocketProvider');
  }
  return context;
};

export const SocketProvider = ({ children }) => {
  const [socket, setSocket] = useState(null);
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const { user } = useAuth();

  useEffect(() => {
    if (!user) {
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    console.log('🔧 Setting up socket connection for user:', user.id);
    
    const token = localStorage.getItem('token');
    // استفاده از متغیر محیطی برای URL اتصال
    const socketUrl = import.meta.env.VITE_WS_URL || 'http://localhost:5000';
    
    const newSocket = io(socketUrl, {
      auth: {
        token: token
      },
      transports: ['websocket', 'polling'],
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000
    });

    newSocket.on('connect', () => {
      console.log('✅ Socket connected successfully:', newSocket.id);
      setIsConnected(true);
      setIsLoading(false);
    });

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

    newSocket.on('connect_error', (error) => {
      console.error('❌ Socket connection error:', error.message || error);
      setIsConnected(false);
      setIsLoading(false);
    });

    newSocket.on('connect_timeout', () => {
      console.error('❌ Socket connection timeout');
      setIsConnected(false);
      setIsLoading(false);
    });

    newSocket.on('reconnect_attempt', (attempt) => {
      console.log(`🔄 Socket reconnect attempt #${attempt}`);
    });

    setSocket(newSocket);

    return () => {
      console.log('🔌 Cleaning up socket connection');
      newSocket.close();
      setSocket(null);
      setIsConnected(false);
      setIsLoading(false);
    };
  }, [user]);

  const value = {
    socket,
    isConnected,
    isLoading
  };

  return (
    <SocketContext.Provider value={value}>
      {children}
    </SocketContext.Provider>
  );
};