import React, { useEffect } from "react";
import { useSelectedComment } from "../../../store/builder/store";
import { useSocketStore } from "../../../store/socket/useSocketStore";
import { getUserData } from "../../../functions/getUserData";
import { getRelativeTime } from "../../../components/ui/collaboration/function/getRelativeTime";
import { useSceneContext } from "../../scene/sceneContext";

interface ThreadSocketProps {
    setMessages: React.Dispatch<React.SetStateAction<Reply[]>>;
    // mode: 'create' | 'edit' | null
    modeRef: React.RefObject<"create" | "edit" | null>;
    messages: Reply[];
}

const ThreadSocketResponsesDev = ({ setMessages, modeRef, messages }: ThreadSocketProps) => {
    const { threadSocket } = useSocketStore();
    const { selectedComment, setSelectedComment, setCommentPositionState, commentPositionState } =
        useSelectedComment();
    const { threadStore } = useSceneContext();
    const { threads, removeReply, addThread, addReply, updateThread, updateReply } = threadStore();
    const { userId } = getUserData();

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

        // --- Add Comment Handler ---
        // const handleAddComment = (data: any) => {
        //
        //
        //     const commentData = {
        //         replyId: data.data?._id,
        //         creatorId: data.data?.userId,
        //         createdAt: getRelativeTime(data.data?.createdAt),
        //         lastUpdatedAt: '2 hrs ago',
        //         comment: data.data.comment,
        //     };
        //     //
        //
        //     if (mode == "create") {
        //         addReply(selectedComment?.threadId, commentData);
        //
        //         setMessages(prevMessages => [...prevMessages, commentData]);
        //     } else if (mode == "edit") {
        //         updateReply(selectedComment?.threadId, data.data?._id, commentData);
        //         setMessages((prev) =>
        //             prev.map((message) => {
        //                  // 👈 log each message
        //                 return (message.replyId || message._id) === data.data?._id
        //                     ? { ...message, comment: data.data?.comment }
        //                     : message;
        //             })
        //         );
        //
        //     } else {
        //
        //     }
        //     threadSocket.off('v1-Comment:response:add', handleAddComment);
        // };
        // threadSocket.on('v1-Comment:response:add', handleAddComment);
        const handleAddComment = (data: any) => {
            const commentData = {
                replyId: data.data?._id,
                creatorId: data.data?.userId,
                createdAt: getRelativeTime(data.data?.createdAt),
                lastUpdatedAt: "2 hrs ago",
                comment: data.data?.comment,
            };

            if (modeRef.current === "create") {
                addReply(selectedComment?.threadId, commentData);
                setMessages((prevMessages) => [...prevMessages, commentData]);
            } else if (modeRef.current === "edit") {
                updateReply(selectedComment?.threadId, data.data?._id, commentData);
                setMessages((prev) =>
                    prev.map((message) => {
                        // 👈 log each message
                        return message.replyId === data.data?._id
                            ? { ...message, comment: data.data?.comment }
                            : message;
                    })
                );
            }
        };
        threadSocket.on("v1-Comment:response:add", handleAddComment);
        // --- Delete Comment Handler ---

        const handleDeleteComment = (data: any) => {};
        threadSocket.on("v1-Comment:response:delete", handleDeleteComment);

        // --- Create Thread Handler ---
        const handleCreateThread = (data: any) => {
            const comment: ThreadSchema = {
                state: "active",
                threadId: data.data?._id,
                creatorId: userId || data.data?.userId,
                createdAt: data.data?.createdAt,
                threadTitle: data.data?.threadTitle,
                lastUpdatedAt: new Date().toISOString(),
                position: commentPositionState.position,
                rotation: [0, 0, 0],
                comments: [],
            };
            setSelectedComment(comment);
            addThread(comment);
            setCommentPositionState(null);
            // setSelectedComment(null);
        };
        threadSocket.on("v1-thread:response:create", handleCreateThread);

        // --- Delete Thread Handler ---
        // const handleDeleteThread = (data: any) => {
        //

        // };
        // threadSocket.on("v1-thread:response:delete", handleDeleteThread);

        const handleDeleteThread = (data: any) => {};
        threadSocket.on("v1-thread:response:delete", handleDeleteThread);

        const handleEditThread = (data: any) => {
            const editedThread: ThreadSchema = {
                state: "active",
                threadId: data.data?._id,
                creatorId: userId,
                createdAt: data.data?.createdAt,
                threadTitle: data.data?.threadTitle,
                lastUpdatedAt: new Date().toISOString(),
                position: data.data?.position,
                rotation: [0, 0, 0],
                comments: data.data?.comments,
            };

            //
            updateThread(data.data?._id, editedThread);
            setSelectedComment(editedThread);

            // setSelectedComment(null);
        };
        threadSocket.on("v1-thread:response:updateTitle", handleEditThread);

        // Cleanup on unmount
        return () => {
            threadSocket.off("v1-Comment:response:add", handleAddComment);
            threadSocket.off("v1-Comment:response:delete", handleDeleteComment);
            threadSocket.off("v1-thread:response:create", handleCreateThread);
            threadSocket.off("v1-thread:response:delete", handleDeleteThread);
            threadSocket.off("v1-thread:response:updateTitle", handleEditThread);
        };
    }, [
        threadSocket,
        selectedComment,
        commentPositionState,
        userId,
        setSelectedComment,
        setCommentPositionState,
        threads,
        modeRef.current,
        messages,
    ]);

    return null;
};

export default ThreadSocketResponsesDev;
