import { FC } from 'react';
import { useAppSelector } from '../../../../redux/hooks';
import MarkdownPreview from '../../../articleeditor/MarckDownPreview';
import { Edit } from '../../../../assets/icons/input';

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 PostItemProps {
    id: number;
    groupId: number;
    authorId: number;
    authorUsername: string;
    name: string;
    content: string;
    createdAt: string;
    updatedAt: string;
    isAdmin: boolean;
    setModalUpdateActive: (v: boolean) => void;
    setUpdatePostId: (v: number) => void;
}

export const PostItem: FC<PostItemProps> = ({
    id,
    authorId,
    authorUsername,
    content,
    createdAt,
    isAdmin,
    setModalUpdateActive,
    setUpdatePostId,
}) => {
    const members = useAppSelector(
        (state) => state.groups.fetchGroupById.group?.members,
    );
    const member = members?.find((m) => m.userId === authorId);

    return (
        <div className="rounded-[10px]  flex flex-col gap-[20px]">
            <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>

                {isAdmin && (
                    <div
                        className=" h-[40px] w-[40px] absolute top-0 right-0 flex items-center justify-center cursor-pointer
                    rounded-[10px] hover:bg-liquid-lighter transition-all duration-300 active:scale-90"
                        onClick={() => {
                            setUpdatePostId(id);
                            setModalUpdateActive(true);
                        }}
                    >
                        <img src={Edit} />
                    </div>
                )}
            </div>

            <div>
                <MarkdownPreview className="bg-transparent" content={content} />
            </div>
        </div>
    );
};
