import React, { useEffect } from "react";
import ThreadInstance from "./threadInstance/threadInstance";
import { getAllThreads } from "../../../../services/factoryBuilder/collab/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 ThreadInstances() {
    const { projectId } = useParams();
    const { userId } = getUserData();
    const { versionStore, threadStore } = useSceneContext();
    const { threads, setThreads } = threadStore();
    const { selectedVersion } = versionStore();

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

    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 ?? "",
                                }))
                              : [],
                      }))
                    : [];
                setThreads(formattedThreads);
            })
            .catch((err) => {
                console.error("Failed to fetch threads:", err);
            });
    }, [projectId, selectedVersion]);

    return (
        <>
            {threads?.map((thread: ThreadSchema) => (
                <React.Fragment key={thread.threadId}>
                    <ThreadInstance thread={thread} />
                </React.Fragment>
            ))}
        </>
    );
}

export default ThreadInstances;
