import { FC } from 'react';
import { useAppSelector } from '../../../../redux/hooks';

function convertDate(isoString: string) {
    const date = new Date(isoString);

    const dd = String(date.getUTCDate()).padStart(2, '0');
    const mm = String(date.getUTCMonth() + 1).padStart(2, '0');
    const yyyy = date.getUTCFullYear();

    const hh = String(date.getUTCHours()).padStart(2, '0');
    const min = String(date.getUTCMinutes()).padStart(2, '0');

    return `${dd}.${mm}.${yyyy} ${hh}:${min}`;
}

interface MessageItemProps {
    id: number;
    groupId: number;
    authorId: number;
    authorUsername: string;
    createdAt: string;
    message: string;
    myMessage: boolean;
}

export const MessageItem: FC<MessageItemProps> = ({
    authorId,
    authorUsername,
    createdAt,
    message,
    myMessage,
}) => {
    const members = useAppSelector(
        (state) => state.groups.fetchGroupById.group?.members,
    );
    const member = members?.find((m) => m.userId === authorId);

    return myMessage ? (
        <div className="flex flex-col gap-[20px] items-end leading-[20px] text-[16px]">
            <div className="w-[50%] flex flex-col gap-[10px]">
                <div className="h-[20px] w-full flex gap-[10px] relative  justify-end ">
                    <div className="font-bold text-liquid-light">
                        {convertDate(createdAt)}
                    </div>
                </div>

                <div className="flex justify-end">
                    <div className="bg-liquid-lighter w-fit max-w-full break-words px-[16px] py-[8px] rounded-[10px] ">
                        {message}
                    </div>
                </div>
            </div>
        </div>
    ) : (
        <div className="flex flex-col gap-[20px] ">
            <div className="w-[50%] flex flex-col gap-[10px]">
                <div className="h-[40px] w-full flex gap-[10px] relative ">
                    <div className="h-[40px] w-[40px] bg-[#D9D9D9] rounded-[10px]"></div>
                    <div className=" leading-[20px] font-bold text-[16px] ">
                        <div>{authorUsername} </div>
                        <div className="text-liquid-light">
                            {member ? member.role : 'роль не найдена'}
                        </div>
                    </div>
                    <div className=" leading-[20px] font-bold text-[16px] ">
                        <div className="text-liquid-light">
                            {convertDate(createdAt)}
                        </div>
                    </div>
                </div>

                <div className="flex">
                    <div className="bg-liquid-lighter w-fit max-w-full break-words px-[16px] py-[8px] rounded-[10px] ">
                        {message}
                    </div>
                </div>
            </div>
        </div>
    );
};
