import { useEffect, useState } from "react";
import io, { Socket } from "socket.io-client";

interface UseEmailWebSocketOptions {
  token: string;
  serverUrl?: string;
  onConnect?: () => void;
  onDisconnect?: () => void;
  onError?: (error: string) => void;
}
export const useEmailWebSocket = ({
  token,
  serverUrl = import.meta.env.VITE_SOCKET_URL,
  onConnect,
  onDisconnect,
  onError,
}: UseEmailWebSocketOptions) => {
  const [socket, setSocket] = useState<Socket | null>(null);
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    if (!token) return;

    const newSocket = io(serverUrl, {
      auth: { token },
      transports: ["websocket", "polling"],
    });

    // Connection events
    newSocket.on("connect", () => {
      console.log("✅ اتصال به WebSocket ایمیل برقرار شد");
      setIsConnected(true);
      onConnect?.();
    });

    newSocket.on("disconnect", () => {
      console.log("❌ اتصال به WebSocket ایمیل قطع شد");
      setIsConnected(false);
      onDisconnect?.();
    });

    newSocket.on("connection_established", (data) => {
      console.log("🎉 اتصال We  bSocket ایمیل تأیید شد:", data);
    });

    newSocket.on("connection_error", (error) => {
      console.error("💥 خطای اتصال WebSocket ایمیل:", error);
      onError?.(error.error);
    });

    // Health monitoring
    newSocket.on("ping", () => {
      newSocket.emit("pong", { timestamp: new Date().toISOString() });
    });

    setSocket(newSocket);

    return () => {
      newSocket.close();
      setSocket(null);
    };
  }, [token, serverUrl]);

  return { socket, isConnected };
};
