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

import { rpc } from '../../../api/request';
import {
  ShmChannelMessageType,
  TypeACFHLPSWEnum,
} from '../../../api/types';
import store from '../../../stores/store';
import Popover from '../../../ui/Popover';
import { reactionsTypes } from './MessageItem';

type MessagePopoverOpenParams = {
  msg: ShmChannelMessageType;
  onChange?: () => void;
};

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

const MessageReactionPopover = forwardRef<MessageReactionPopoverRefProps>(
  (_, ref) => {
    const [msg, setMsg] = useState<ShmChannelMessageType | null>(null);
    const [open, setOpen] = useState(false);
    const [target, setTarget] = useState<HTMLElement | null>(null);
    const openParamsRef = useRef<MessagePopoverOpenParams | null>(null);

    useImperativeHandle(ref, () => ({
      open: (params) => {
        setMsg(params.msg);
        setTarget(
          document.getElementById(`msg-add-reactions-${params.msg._id}`) ||
            document.getElementById(`msg-${params.msg._id}`)
        );
        setOpen(true);
        openParamsRef.current = params;
      },
    }));

    const onClose = () => {
      setOpen(false);
      setTarget(null);
    };

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

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

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

    return (
      <Popover opened={open} onClose={onClose} target={target} width={320}>
        <div className="p-2 grid grid-cols-5 gap-1">
          {reactionsTypes.map((reaction) => {
            const active = selectReaction?.type === reaction.value;
            return (
              <button
                type="button"
                key={reaction.value}
                onClick={() => sendReaction(reaction.value)}
                className={`
                  h-12 inline-flex items-center justify-center rounded-xl
                  text-[26px] tg-press
                  ${active ? 'bg-[var(--tg-accent-soft)]' : 'hover:bg-[var(--tg-bg-secondary)]'}
                `}
                title={reaction.label}
              >
                {reaction.name}
              </button>
            );
          })}
        </div>
      </Popover>
    );
  }
);

MessageReactionPopover.displayName = 'MessageReactionPopover';

export default MessageReactionPopover;
