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 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 reply = ExtensionsStore.shmChannelMessagesByID(msg.reply);




    const isDeleted = !!msg.deleted;

    const isSystemMessage = msg.type == "system";

    if (isSystemMessage) {
        return <div className='text-sm  text-center p-6 opacity-70'>{msg.text}</div>
    }

    return (
        <>
            <Message




                onClick={() => {

                    if (!isDeleted) {
                        onClick();
                    }

                }}
                key={msg._id}
                type={msg.owner != store.userID ? "received" : "sent"}
                name={msg.owner ?? ""}
                //@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.owner != store.userID && msg.avatar && (
                      <img
                          alt="avatar"
                          src={msg.avatar}
                          className="w-8 h-8 rounded-full"
                      />
                  )
              }*/
            />



        </>

    );
};

export default MessageItem;
