import 'dayjs/locale/ru'; // load on demand

import dayjs from 'dayjs';
import {
  Chip,
  Message,
} from 'konsta/react';
import _ from 'lodash';
import { BsTrash3 } from 'react-icons/bs';
import { FiExternalLink } from 'react-icons/fi';

import {
  ExtensionsStore,
  rpc,
} from '../../../api/request';
import {
  ShmChannelMessageType,
  TypeACFHLPSWEnum,
} from '../../../api/types';
import store from '../../../stores/store';
import AudioPlayer from './AudioPlayer';
import FileTypeIcon from './FileTypeIcon';
import MessageReplayItem from './MessageReplayItem';

dayjs.locale("ru");


export const reactionsTypes: {
    name: string;
    value: TypeACFHLPSWEnum;
}[] = [
        { name: "❤️", value: "heart" },
        { name: "👍", value: "like" },
        { name: "😂", value: "laugh" },
        { name: "😮", value: "wow" },
        { name: "😢", value: "sad" },
        { name: "😡", value: "angry" },
        { name: "👏", value: "clap" },
        { name: "🎉", value: "party" },
        { name: "💩", value: "poop" },
        { name: "🔥", value: "fire" },
    ];


const findNameByReaction = (reaction: TypeACFHLPSWEnum) => {
    const reactionType = reactionsTypes.find((r) => r.value === reaction);
    return reactionType ? reactionType.name : "";
}


const MessageItem = ({
    onReplayClick,
    msg,
    onClick,
    onChange
}: {
    onReplayClick: (msg: ShmChannelMessageType) => void;
    msg: ShmChannelMessageType;
    onChange: () => void;
    onClick: () => void;
}) => {

    const { userID } = store;




    const sendReaction = (reaction: TypeACFHLPSWEnum) => {



        rpc.channelReaction({
            message: msg._id,
            channel: msg.channel,
            reaction: reaction,
        }).then(() => {

            onChange();

        });

    }


    const MsgTotalReactions = () => {

        if (!msg.reactions || msg.reactions.length == 0) return null;

        const data = _.groupBy(msg.reactions, (r) => r.type);

        return (
            <div className="flex items-center space-x-1 mt-2">
                {_.map(data, (reactions, type) => {
                    return (
                        <Chip

                            onClick={(e) => {
                                e.stopPropagation();
                                // e.preventDefault();
                                sendReaction(type as TypeACFHLPSWEnum);
                            }}

                            media={<div className='ml-2'>{findNameByReaction(type as TypeACFHLPSWEnum)}</div>}
                            key={type}

                            className="m-1 cursor-pointer"
                        >
                            <span className='font-medium'>{reactions.length}</span>
                        </Chip>
                    );
                })}
            </div>
        );

    }



    const member = ExtensionsStore.shmChannelMembersByID(msg.member);


    const reply = ExtensionsStore.shmChannelMessagesByID(msg.reply);




    const isDeleted = !!msg.deleted;

    return (
        <>
            <Message




                onClick={onClick}
                key={msg._id}
                type={msg.member != userID ? "received" : "sent"}
                name={member?.name ?? ""}
                //@ts-ignore


                text={isDeleted ? <div className='opacity-80 text-sm flex items-center gap-2'><BsTrash3 className='w-4 h-4' /> Сообщение удалено</div> :
                    <div id={`msg-${msg._id}`}>


                        {!!reply && <MessageReplayItem msg={reply}
                            onClick={() => {

                                if (reply)
                                    onReplayClick(reply);

                            }}
                        />}

                        <div>{msg.text}</div>


                        {msg.voice?.url && <AudioPlayer src={msg.voice?.url} cacheKey={msg._id} />}

                        {msg.attachments?.map((attachment) => {

                            return <div

                                className="cursor-pointer active:opacity-50 flex items-center space-x-2"
                            >


                                <FileTypeIcon doc={attachment} />

                                <div>{attachment.name}</div>
                                <div
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        // e.preventDefault();

                                        window.open(attachment.url, "_blank");
                                    }}
                                >
                                    <FiExternalLink />
                                </div>
                            </div>

                        })}


                        <MsgTotalReactions />
                    </div>
                }
                footer={
                    <div>

                        {msg.created_at &&
                            dayjs.unix(msg.created_at).format("DD.MM hh:mm")}
                    </div>
                }
                avatar={
                    msg.member != userID && member?.avatar && (
                        <img
                            alt="avatar"
                            src={member?.avatar}
                            className="w-8 h-8 rounded-full"
                        />
                    )
                }
            />



        </>

    );
};

export default MessageItem;
