import { useEffect, useState, useCallback } from "react";
import {
  socketService,
  Message,
  UnreadMessage,
} from "../service/SocketService";

export interface UseSocketReturn {
  isConnected: boolean;
  connect: () => Promise<void>;
  disconnect: () => void;
  joinChat: (chatId: string) => void;
  leaveChat: (chatId: string) => void;
  sendMessage: (chatId: string, content: string, receiver: string) => void;
  onNewMessage: (callback: (message: Message) => void) => void;
  onUnreadMessages: (callback: (messages: UnreadMessage[]) => void) => void;
  onUserOnline: (callback: (userId: string) => void) => void;
  onUserOffline: (callback: (userId: string) => void) => void;
  onError: (callback: (error: unknown) => void) => void;
  offNewMessage: (callback: (message: Message) => void) => void;
  offUnreadMessages: (callback: (messages: UnreadMessage[]) => void) => void;
  offUserOnline: (callback: (userId: string) => void) => void;
  offUserOffline: (callback: (userId: string) => void) => void;
  offError: (callback: (error: unknown) => void) => void;
}

export const useSocket = (): UseSocketReturn => {
  const [isConnected, setIsConnected] = useState(false);

  // اتصال به سوکت
  const connect = useCallback(async () => {
    if (isConnected) return;

    try {
      console.log("🔌 شروع اتصال به سوکت...");
      await socketService.connect("User");
      setIsConnected(true);
      console.log("✅ سوکت متصل شد");
    } catch (error) {
      console.error("❌ خطا در اتصال سوکت:", error);
      throw error;
    }
  }, [isConnected]);

  // قطع اتصال سوکت
  const disconnect = useCallback(() => {
    console.log("🔌 قطع اتصال سوکت");
    socketService.disconnect();
    setIsConnected(false);
  }, []);

  // ورود به چت
  const joinChat = useCallback((chatId: string) => {
    socketService.joinChat(chatId);
  }, []);

  // خروج از چت
  const leaveChat = useCallback((chatId: string) => {
    socketService.leaveChat(chatId);
  }, []);

  // ارسال پیام
  const sendMessage = useCallback(
    (chatId: string, content: string, receiver: string) => {
      socketService.sendMessage(chatId, content, receiver);
    },
    []
  );

  // Event listeners
  const onNewMessage = useCallback((callback: (message: Message) => void) => {
    socketService.on("newMessage", callback as (data: unknown) => void);
  }, []);

  const onUnreadMessages = useCallback(
    (callback: (messages: UnreadMessage[]) => void) => {
      socketService.on("unreadMessages", callback as (data: unknown) => void);
    },
    []
  );

  const onUserOnline = useCallback((callback: (userId: string) => void) => {
    socketService.on("userOnline", callback as (data: unknown) => void);
  }, []);

  const onUserOffline = useCallback((callback: (userId: string) => void) => {
    socketService.on("userOffline", callback as (data: unknown) => void);
  }, []);

  const onError = useCallback((callback: (error: unknown) => void) => {
    socketService.on("error", callback);
  }, []);

  // Remove event listeners
  const offNewMessage = useCallback((callback: (message: Message) => void) => {
    socketService.off("newMessage", callback as (data: unknown) => void);
  }, []);

  const offUnreadMessages = useCallback(
    (callback: (messages: UnreadMessage[]) => void) => {
      socketService.off("unreadMessages", callback as (data: unknown) => void);
    },
    []
  );

  const offUserOnline = useCallback((callback: (userId: string) => void) => {
    socketService.off("userOnline", callback as (data: unknown) => void);
  }, []);

  const offUserOffline = useCallback((callback: (userId: string) => void) => {
    socketService.off("userOffline", callback as (data: unknown) => void);
  }, []);

  const offError = useCallback((callback: (error: unknown) => void) => {
    socketService.off("error", callback);
  }, []);

  // تنظیم وضعیت اتصال
  useEffect(() => {
    const handleConnect = () => {
      console.log("📡 سوکت متصل شد");
      setIsConnected(true);
    };

    const handleDisconnect = () => {
      console.log("📡 سوکت قطع شد");
      setIsConnected(false);
    };

    socketService.on("connect", handleConnect);
    socketService.on("disconnect", handleDisconnect);

    // بررسی وضعیت اولیه
    setIsConnected(socketService.isConnected());

    return () => {
      socketService.off("connect", handleConnect);
      socketService.off("disconnect", handleDisconnect);
    };
  }, []);

  return {
    isConnected,
    connect,
    disconnect,
    joinChat,
    leaveChat,
    sendMessage,
    onNewMessage,
    onUnreadMessages,
    onUserOnline,
    onUserOffline,
    onError,
    offNewMessage,
    offUnreadMessages,
    offUserOnline,
    offUserOffline,
    offError,
  };
};
