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 { useVersionContext } from '../../../builder/version/versionContext';

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

    const getThreads = async () => {
        if (!projectId || !selectedVersion) return;
        try {
            const getComments = await getAllThreads(projectId, selectedVersion?.versionId);

            const formattedThreads = Array.isArray(getComments.data)
                ? getComments.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);
        }
    }

    useEffect(() => {
        getThreads();
    }, []);

    useEffect(() => {
        // console.log("comments", comments);
    }, [comments])
    return (
        <>
            {comments?.map((comment: CommentSchema) => (
                <React.Fragment key={comment.threadId}>
                    <CommentInstance comment={comment} />
                </React.Fragment>
            ))}
        </>
    )
}

export default CommentInstances