import React, { useState } from "react";
import { getAvatarColor } from "../../../../modules/collaboration/functions/getAvatarColor";
import { getUserData } from "../../../../functions/getUserData";
import { getRelativeTime } from "../function/getRelativeTime";

interface CommentThreadsProps {
    commentClicked: () => void;
    comment?: CommentSchema;
}

const CommentThreads: React.FC<CommentThreadsProps> = ({ commentClicked, comment }) => {
    const [expand, setExpand] = useState(false);
    const commentsedUsers = [{ creatorId: "1" }];
    const { userName } = getUserData();

    function getUsername(userId: string) {
        const UserName = userName?.charAt(0).toUpperCase() || "user";
        return UserName;
    }

    function getDetails(type?: "clicked") {
        if (type === "clicked") {
            setExpand(true);
            commentClicked();
        } else {
            setExpand((prev) => !prev);
        }
    }

    return (
        <div className="comments-threads-wrapper">
            <button
                onPointerEnter={() => getDetails()}
                onPointerLeave={() => getDetails()}
                onClick={() => getDetails("clicked")}
                className={`comments-threads-container ${expand ? "open" : "closed"} unread`}
            >
                <div className="users-commented">
                    {commentsedUsers.map((val, i) => (
                        <div
                            className="users"
                            key={val.creatorId}
                            style={{
                                background: getAvatarColor(i, getUsername(val.creatorId)),
                            }}
                        >
                            {getUsername(val.creatorId)[0]}
                        </div>
                    ))}
                </div>
                <div className={`last-comment-details ${expand ? "expand" : ""}`}>
                    <div className="header">
                        <div className="user-name">{userName}</div>
                        <div className="time">{comment?.createdAt && getRelativeTime(comment.createdAt)}</div>
                    </div>
                    <div className="message">{comment?.threadTitle}</div>
                    {comment && comment?.comments.length > 0 && (
                        <div className="comments">
                            {comment?.comments.length} {comment?.comments.length === 1 ? "comment" : "replies"}
                        </div>
                    )}
                </div>
            </button>
        </div>
    );
};

export default CommentThreads;
