import {
    forwardRef,
    useImperativeHandle,
    useRef,
    useState,
} from 'react';

import {
    List,
    ListItem,
    Popover,
} from 'konsta/react';
import { LuCheck } from 'react-icons/lu';

import { rpc } from '../../../api/request';
import {
    ShmChannelMessageType,
    TypeACFHLPSWEnum,
} from '../../../api/types';
import { toast } from '../../../components/ToastRoot';
import store from '../../../stores/store';
import { reactionsTypes } from './MessageItem';

type MessagePopoverOpenParams = {
    onReply?: (msg: ShmChannelMessageType) => void,
    onPinned?: () => void,
    onDelete?: () => void,
    msg: ShmChannelMessageType,

    onChange?: () => void
}

export type MessagePopoverRefProps = {
    open: (params: MessagePopoverOpenParams) => void,
}

const copyToClipboard = (text?: string) => {
    if (!text) return;
    navigator.clipboard.writeText(text);
    toast("Текст сообщения скопирован в буфер обмена");
}
const MessagePopover = forwardRef<MessagePopoverRefProps>((props, ref) => {




    const [msg, setMsg] = useState<ShmChannelMessageType | null>(null);


    const openParamsRef = useRef<MessagePopoverOpenParams | null>(null);

    useImperativeHandle(ref, () => ({
        open: (params) => {
            setOpen(true);
            setMsg(params.msg);
            openParamsRef.current = params;
        }
    }));



    const [open, setOpen] = useState(false);


    const onClose = () => {
        setOpen(false);

    }
    const sendReaction = (reaction: TypeACFHLPSWEnum) => {


        onClose();
        rpc.channelReaction({
            channel: msg?.channel,
            message: msg?._id,
            reaction: reaction,
        }).then(() => {
            openParamsRef.current?.onChange?.();


        });

    }



    const ReactionsBlock = () => {





        const selectReaction = msg?.reactions?.find((r) => r.user == store.userID);


        return <List nested outline dividers>
            {reactionsTypes.map((reaction, index) => {
                return <ListItem
                    title={`${reaction.label}`}
                    media={<div className='ml-2'>{reaction.name}</div>}
                    link
                    chevron={false}
                    after={selectReaction?.type == reaction.value ? <LuCheck className='w-4 h-4' /> : null}
                    onClick={() => {
                        sendReaction(reaction.value as TypeACFHLPSWEnum);
                    }}
                />
            })}
        </List>



    }



    const canDelete = msg?.owner == store.userID;


    if (!open || !msg?._id) return null;




    return (
        <Popover
            opened={open && !!msg?._id}
            target={`#msg-${msg?._id}`}
            onBackdropClick={onClose}

        >

            <List nested outline dividers>



                <ListItem
                    title="Ответить"
                    link
                    onClick={() => {
                        if (!msg) return;
                        openParamsRef.current?.onReply?.(msg);
                        onClose();
                    }}
                />
                {!!msg.text && <ListItem
                    title="Копировать текст"
                    link
                    onClick={() => {
                        if (!msg) return;

                        copyToClipboard(msg.text);

                        onClose();
                    }}
                />}
                <ListItem
                    title={msg?.pinned?.enabled ? "Убрать закрепление" : "Закрепить"}
                    link
                    onClick={() => {
                        if (!msg) return;
                        openParamsRef.current?.onPinned?.();
                        onClose();
                    }}
                />

                {canDelete && <ListItem

                    title={<span className="text-red-500">Удалить</span>}
                    link
                    onClick={() => {

                        if (!msg) return;
                        openParamsRef.current?.onDelete?.();
                        onClose();

                    }}
                />}
            </List>
        </Popover>
    );
});


export default MessagePopover;