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 store from '../../../stores/store';
import { reactionsTypes } from './MessageItem';

type MessagePopoverOpenParams = {

    msg: ShmChannelMessageType,

    onChange?: () => void
}

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


const MessageReactionPopover = forwardRef<MessageReactionPopoverRefProps>((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>



    }



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



    return <Popover
        opened={open && !!msg?._id}
        target={`#msg-add-reactions-${msg?._id}`}
        onBackdropClick={onClose}
        className='w-[300px]'
    >
        <ReactionsBlock />
    </Popover>



});


export default MessageReactionPopover;