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

import dayjs from 'dayjs';
import emojiRegex from 'emoji-regex';
import {
  Chip,
  Link,
  Message,
} from 'konsta/react';
import _ from 'lodash';
import { BsTrash3 } from 'react-icons/bs';
import { FiExternalLink } from 'react-icons/fi';
import { IoCheckmarkDoneSharp } from 'react-icons/io5';
import { LuSmilePlus } from 'react-icons/lu';

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

dayjs.locale("ru");


export const reactionsTypes: {
    name: string;
    label: string;
    value: TypeACFHLPSWEnum;
}[] = [
        { name: "❤️", label: "Сердце", value: "heart" },
        { name: "👍", label: "Лайк", value: "like" },
        { name: "😂", label: "Смех", value: "laugh" },
        { name: "😮", label: "Удивление", value: "wow" },
        { name: "😢", label: "Грусть", value: "sad" },
        { name: "😡", label: "Злость", value: "angry" },
        { name: "👏", label: "Аплодисменты", value: "clap" },
        { name: "🎉", label: "Праздник", value: "party" },
        { name: "💩", label: "Стыд", value: "poop" },
        { name: "🔥", label: "Огонь", value: "fire" },
    ];


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



export function isValidEmojiString(input?: string): boolean {
    if (!input) return false;
    const regex = emojiRegex();
    const matches = input.match(regex);

    if (!matches) return false;

    // Проверяем, что вся строка состоит только из emoji
    const isOnlyEmoji = matches.join('') === input;

    // Проверяем количество emoji
    const isValidLength = matches.length <= 8;

    return isOnlyEmoji && isValidLength;
}

const MessageItem = ({
    onReplayClick,
    onReactionClick,
    msg,
    onClick,
    onChange
}: {
    onReplayClick: (msg: ShmChannelMessageType) => void;
    msg: ShmChannelMessageType;
    onChange: () => void;
    onClick: () => void;
    onReactionClick: (msg: ShmChannelMessageType) => 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>
    }

    const isDarkTheme = document.body.classList.contains('dark');

    const onlyEmoji = isValidEmojiString(msg.text);
    return (
        <>
            <Message



                className={`${onlyEmoji ? 'only-emoji-msg' : ''}`}


                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

                            style={{
                                fontSize: onlyEmoji ? 50 : undefined,
                            }}

                        >{msg.text}</div>


                        {msg.voice?.url && <AudioPlayer


                            barColor={isDarkTheme ? msg.owner == store.userID ? '#000' : '#fff' : msg.owner == store.userID ? '#fff' : '#000'}

                            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 />

                        {msg.owner != store.userID ? <><div

                            onClick={(e) => {

                                onReactionClick(msg);
                                e.stopPropagation();
                                e.preventDefault();
                            }}

                            id={`msg-add-reactions-${msg._id}`}
                            className="absolute top-3 -right-6">
                            <Link>
                                <LuSmilePlus className='w-4 h-4' />
                            </Link>

                        </div>





                        </> : <>

                            {/*
                            
                            На свои сообщения нельзя реагировать

                            <div

                            onClick={(e) => {

                                onReactionClick(msg);
                                e.stopPropagation();
                                e.preventDefault();
                            }}
                            id={`msg-add-reactions-${msg._id}`}
                            className="absolute top-3 -left-6">
                            <Link>
                                <LuSmilePlus className='w-4 h-4' />
                            </Link>

                        </div>*/}
                        </>}
                    </div>
                }
                footer={
                    <div className='flex items-center gap-1'>

                        {msg.created_at &&
                            dayjs.unix(msg.created_at).format("DD.MM HH:mm")}

                        {msg.owner == store.userID && msg.viewed && <IoCheckmarkDoneSharp size={16} className=' text-gray-500' />}
                    </div>
                }
                avatar={
                    msg.owner != store.userID && <div className='bg-white dark:bg-gray-800 border-2 border-gray-200 dark:border-gray-700 text-xl rounded-full w-8 h-8 flex items-center justify-center -mt-5'>
                        {emojiFromId(msg.owner ?? "")}
                    </div>
                }
            >


            </Message>



        </>

    );
};

export default MessageItem;
