"use client";

import { useEffect, useCallback } from "react";
import { chatbotSocketService } from "../service/SocketService";
import { useChatbotStore } from "../store/ChatbotStore";
import {
  SessionCreatedResponse,
  ChatJoinedResponse,
  MessageReceivedResponse,
  BotResponse,
  BotResponseStart,
  BotResponseChunk,
  BotResponseEnd,
  ErrorResponse,
} from "../types/Types";
import { toast } from "@/components/Toast";

export function useChatbotSocket() {
  const {
    setConnectionStatus,
    setCurrentSession,
    addMessage,
    setMessages,
    startStreaming,
    appendStreamChunk,
    endStreaming,
    addSession,
    setError,
  } = useChatbotStore();

  const connect = useCallback(async () => {
    try {
      await chatbotSocketService.connect();
    } catch (error) {
      console.error("خطا در اتصال:", error);
      toast("خطا در اتصال به سرور", "error");
    }
  }, []);

  const disconnect = useCallback(() => {
    chatbotSocketService.disconnect();
  }, []);

  const createSession = useCallback(() => {
    if (chatbotSocketService.isConnected()) {
      chatbotSocketService.createSession();
    } else {
      toast("ابتدا به سرور متصل شوید", "error");
    }
  }, []);

  const joinSession = useCallback((sessionId: string) => {
    if (chatbotSocketService.isConnected()) {
      chatbotSocketService.joinChat(sessionId);
    } else {
      toast("ابتدا به سرور متصل شوید", "error");
    }
  }, []);

  const sendMessage = useCallback(
    (content: string, useStreaming: boolean = true) => {
      const { currentSession } = useChatbotStore.getState();
      if (!currentSession) {
        toast("لطفا ابتدا یک سشن ایجاد کنید", "error");
        return;
      }

      if (chatbotSocketService.isConnected()) {
        const payload = {
          content,
          sessionId: currentSession.id,
        };

        if (useStreaming) {
          chatbotSocketService.sendMessageStream(payload);
        } else {
          chatbotSocketService.sendMessage(payload);
        }
      } else {
        toast("ابتدا به سرور متصل شوید", "error");
      }
    },
    []
  );

  useEffect(() => {
    // Connection status listener
    const handleConnectionStatus = (status: unknown) => {
      setConnectionStatus(
        status as
          | "disconnected"
          | "connecting"
          | "connected"
          | "reconnecting"
          | "error"
      );
    };

    // Session created
    const handleSessionCreated = (data: unknown) => {
      const response = data as SessionCreatedResponse;
      if (response.status === "success") {
        setCurrentSession(response.data);
        addSession(response.data);
        setMessages(response.data.messages);
        // toast را حذف کردیم چون به صورت خودکار ایجاد می‌شود
      }
    };

    // Chat joined
    const handleChatJoined = (data: unknown) => {
      const response = data as ChatJoinedResponse;
      if (response.status === "success") {
        setCurrentSession(response.data);
        setMessages(response.data.messages);
      }
    };

    // Message received
    const handleMessageReceived = (data: unknown) => {
      const response = data as MessageReceivedResponse;
      if (response.status === "success") {
        addMessage(response.data);
      }
    };

    // Bot response (non-streaming)
    const handleBotResponse = (data: unknown) => {
      const response = data as BotResponse;
      if (response.status === "success") {
        // بررسی اینکه آیا message موقت از streaming وجود دارد
        const { messages } = useChatbotStore.getState();
        const tempMessageIndex = messages.findIndex(
          (msg) =>
            msg.id.startsWith("streaming-") &&
            msg.responseToId === response.data.responseToId
        );
        if (tempMessageIndex !== -1) {
          // جایگزینی message موقت با message واقعی
          useChatbotStore
            .getState()
            .updateMessage(messages[tempMessageIndex].id, response.data);
        } else {
          // اگر message موقت پیدا نشد، message جدید اضافه کن
          addMessage(response.data);
        }
      }
    };

    // Bot response start (streaming)
    const handleBotResponseStart = (data: unknown) => {
      const response = data as BotResponseStart;
      if (response.status === "success") {
        startStreaming(response.data.userMessageId);
      }
    };

    // Bot response chunk (streaming)
    const handleBotResponseChunk = (data: unknown) => {
      const response = data as BotResponseChunk;
      if (response.status === "success") {
        appendStreamChunk(response.data.chunk);
      }
    };

    // Bot response end (streaming)
    const handleBotResponseEnd = (data: unknown) => {
      const response = data as BotResponseEnd;
      if (response.status === "success") {
        endStreaming(response.data.fullResponse);
      }
    };

    // Error handlers
    const handleError = (data: unknown) => {
      const error = data as ErrorResponse;
      setError(error.message);
      toast(error.message, "error");
    };

    const handleSessionError = (data: unknown) => {
      const error = data as ErrorResponse;
      toast(`خطای سشن: ${error.message}`, "error");
    };

    const handleMessageError = (data: unknown) => {
      const error = data as ErrorResponse;
      toast(`خطای پیام: ${error.message}`, "error");
    };

    // Register listeners
    chatbotSocketService.on(
      "connection_status_changed",
      handleConnectionStatus
    );
    chatbotSocketService.on("session_created", handleSessionCreated);
    chatbotSocketService.on("chat_joined", handleChatJoined);
    chatbotSocketService.on("message_received", handleMessageReceived);
    chatbotSocketService.on("bot_response", handleBotResponse);
    chatbotSocketService.on("bot_response_start", handleBotResponseStart);
    chatbotSocketService.on("bot_response_chunk", handleBotResponseChunk);
    chatbotSocketService.on("bot_response_end", handleBotResponseEnd);
    chatbotSocketService.on("error", handleError);
    chatbotSocketService.on("session_error", handleSessionError);
    chatbotSocketService.on("message_error", handleMessageError);

    // Cleanup
    return () => {
      chatbotSocketService.off(
        "connection_status_changed",
        handleConnectionStatus
      );
      chatbotSocketService.off("session_created", handleSessionCreated);
      chatbotSocketService.off("chat_joined", handleChatJoined);
      chatbotSocketService.off("message_received", handleMessageReceived);
      chatbotSocketService.off("bot_response", handleBotResponse);
      chatbotSocketService.off("bot_response_start", handleBotResponseStart);
      chatbotSocketService.off("bot_response_chunk", handleBotResponseChunk);
      chatbotSocketService.off("bot_response_end", handleBotResponseEnd);
      chatbotSocketService.off("error", handleError);
      chatbotSocketService.off("session_error", handleSessionError);
      chatbotSocketService.off("message_error", handleMessageError);
    };
  }, [
    setConnectionStatus,
    setCurrentSession,
    addMessage,
    setMessages,
    startStreaming,
    appendStreamChunk,
    endStreaming,
    addSession,
    setError,
  ]);

  return {
    connect,
    disconnect,
    createSession,
    joinSession,
    sendMessage,
    isConnected: chatbotSocketService.isConnected(),
    connectionStatus: chatbotSocketService.getConnectionStatus(),
  };
}
