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

import {
  Chip,
  List,
  ListItem,
  Popover,
} from 'konsta/react';

import { rpc } from '../../../api/request';
import {
  ShmChannelMessageType,
  TypeACFHLPSWEnum,
} from '../../../api/types';
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 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 (
            <div className=" p-2">
                <div className='flex  justify-around items-center'>
                    {reactionsTypes.map((reaction, index) => {
                        if (index < 5)
                            return (
                                <Chip

                                    outline={selectReaction?.type != reaction.value}
                                    key={reaction.value}
                                    className="m-1 cursor-pointer"
                                    onClick={() => {
                                        sendReaction(reaction.value as TypeACFHLPSWEnum);
                                    }}
                                >
                                    {reaction.name}
                                </Chip>
                            );
                    })}
                </div>

                <div className='flex  justify-around items-center'>
                    {reactionsTypes.map((reaction, index) => {
                        if (index >= 5)
                            return (
                                <Chip
                                    outline={selectReaction?.type != reaction.value}
                                    key={reaction.value}
                                    className="m-1 cursor-pointer"
                                    onClick={() => {
                                        sendReaction(reaction.value as TypeACFHLPSWEnum);
                                    }}
                                >
                                    {reaction.name}
                                </Chip>
                            );
                    })}
                </div>
            </div>
        );

    }


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


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

    return (
        <Popover
            opened={open && !!msg?._id}
            target={`#msg-${msg?._id}`}
            onBackdropClick={onClose}
            className='w-[300px]'
        >
            <ReactionsBlock />
            <List nested>
                <ListItem
                    title="Ответить"
                    link
                    onClick={() => {
                        if (!msg) return;
                        openParamsRef.current?.onReply?.(msg);
                        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;