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;
    thread?: ThreadSchema;
}

const CommentThreads: React.FC<CommentThreadsProps> = ({ commentClicked, thread }) => {
    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">{thread?.createdAt && getRelativeTime(thread.createdAt)}</div>
                    </div>
                    <div className="message">{thread?.threadTitle}</div>
                    {thread && thread?.comments.length > 0 && (
                        <div className="comments">
                            {thread?.comments.length} {thread?.comments.length === 1 ? "comment" : "replies"}
                        </div>
                    )}
                </div>
            </button>
        </div>
    );
};

export default CommentThreads;
