import React, { useEffect } from 'react';
import { useSelectedComment, useSocketStore } from '../../../store/builder/store';
import { useCommentStore } from '../../../store/collaboration/useCommentStore';
import { getUserData } from '../../../functions/getUserData';
import { getRelativeTime } from '../../../components/ui/collaboration/function/getRelativeTime';

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 { comments, removeReply, addComment, addReply, updateComment, updateReply } = useCommentStore();
    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;
                    })
                );

            } else {

            }

        };
        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: CommentSchema = {
                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)
            addComment(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: CommentSchema = {
                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,
            };

            // 
            updateComment(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, setMessages, addReply, addComment, setSelectedComment, setCommentPositionState, updateComment, comments, modeRef.current, messages]);

    return null;
};

export default ThreadSocketResponsesDev;
