import React, { useEffect } from "react";
import CommentInstance from "./commentInstance/commentInstance";
import { useCommentStore } from "../../../../store/collaboration/useCommentStore";
import { getAllThreads } from "../../../../services/factoryBuilder/comments/getAllThreads";
import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
import { getRelativeTime } from "../../../../components/ui/collaboration/function/getRelativeTime";
import { useSceneContext } from "../../../scene/sceneContext";

function CommentInstances() {
    const { comments, setComments } = useCommentStore();
    const { projectId } = useParams();
    const { userId } = getUserData();
    const { versionStore } = useSceneContext();
    const { selectedVersion } = versionStore();

    useEffect(() => {
        // console.log("comments", comments);
    }, [comments]);

    useEffect(() => {
        if (!projectId || !selectedVersion) return;
        getAllThreads(projectId, selectedVersion?.versionId)
            .then((fetchedComments) => {
                const formattedThreads = Array.isArray(fetchedComments.data)
                    ? fetchedComments.data.map((thread: any) => ({
                          ...thread,
                          comments: Array.isArray(thread.comments)
                              ? thread.comments.map((val: any) => ({
                                    replyId: val._id ?? "",
                                    creatorId: userId,
                                    createdAt: getRelativeTime(val.createdAt),
                                    lastUpdatedAt: "1 hr ago",
                                    comment: val.comment,
                                    _id: val._id ?? "",
                                }))
                              : [],
                      }))
                    : [];
                setComments(formattedThreads);
            })
            .catch((err) => {
                console.error("Failed to fetch threads:", err);
            });
    }, []);

    return (
        <>
            {comments?.map((comment: CommentSchema) => (
                <React.Fragment key={comment.threadId}>
                    <CommentInstance comment={comment} />
                </React.Fragment>
            ))}
        </>
    );
}

export default CommentInstances;
