import React, { MouseEventHandler, useEffect, useRef, useState } from 'react';
import { Box, IconButton, Menu, PopOut } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { Room } from 'matrix-js-sdk';
import { EmojiBoard } from '../../components/emoji-board';
import { copyToClipboard } from '../../utils/dom';
import { PluginButtonSlot } from '../settings/plugins/PluginButtonSlot';
import { useForumMessageMenu } from './ForumMessageMenuContext';
import * as theme from './forumTheme.css';

type ForumMessageActionsProps = {
  imagePackRooms: Room[];
  eventId?: string;
  body?: string;
  canSendReaction?: boolean;
  onReactionToggle?: (targetEventId: string, key: string, shortcode?: string) => void;
  onReply: () => void;
  replyActive?: boolean;
  onEdit?: () => void;
  canEdit?: boolean;
  onDelete?: () => void;
  canDelete?: boolean;
};

export function ForumMessageActions({
  imagePackRooms,
  eventId,
  body,
  canSendReaction,
  onReactionToggle,
  onReply,
  replyActive,
  onEdit,
  canEdit,
  onDelete,
  canDelete,
}: ForumMessageActionsProps) {
  const menu = useForumMessageMenu();
  const emojiBtnRef = useRef<HTMLButtonElement>(null);
  const [emojiBoardAnchor, setEmojiBoardAnchor] = useState<DOMRect>();
  const [shiftHeld, setShiftHeld] = useState(false);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Shift') setShiftHeld(true);
    };
    const handleKeyUp = (e: KeyboardEvent) => {
      if (e.key === 'Shift') setShiftHeld(false);
    };
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, []);

  const handleOpenEmojiBoard: MouseEventHandler<HTMLButtonElement> = () => {
    setEmojiBoardAnchor(emojiBtnRef.current?.getBoundingClientRect());
  };

  const handleOpenMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
    const target = evt.currentTarget.parentElement ?? evt.currentTarget;
    menu?.openMenu(target.getBoundingClientRect());
  };

  const handleReplyClick: MouseEventHandler<HTMLButtonElement> = (evt) => {
    evt.stopPropagation();
    onReply();
  };

  return (
    <Menu className={theme.ForumMessageOptionsBar} variant="SurfaceVariant">
      <Box gap="100" direction="Row" alignItems="Center">
      {canSendReaction && eventId && onReactionToggle && (
        <PopOut
          position="Bottom"
          align="End"
          anchor={emojiBoardAnchor}
          content={
            <EmojiBoard
              imagePackRooms={imagePackRooms}
              returnFocusOnDeactivate={false}
              allowTextCustomEmoji
              onEmojiSelect={(key) => {
                onReactionToggle(eventId, key);
                setEmojiBoardAnchor(undefined);
              }}
              onCustomEmojiSelect={(mxc, shortcode) => {
                onReactionToggle(eventId, mxc, shortcode);
                setEmojiBoardAnchor(undefined);
              }}
              requestClose={() => setEmojiBoardAnchor(undefined)}
            />
          }
        >
          <IconButton
            ref={emojiBtnRef}
            onClick={handleOpenEmojiBoard}
            variant="SurfaceVariant"
            size="300"
            radii="300"
            aria-label="Add reaction"
            title="Add reaction"
            aria-pressed={!!emojiBoardAnchor}
          >
            <Icon src={Icons.SmilePlus} size="100" />
          </IconButton>
        </PopOut>
      )}
      <IconButton
        onClick={handleReplyClick}
        variant="SurfaceVariant"
        size="300"
        radii="300"
        aria-label="Reply"
        title="Reply"
        aria-pressed={replyActive}
        className={replyActive ? theme.ForumMessageActionBtnActive : undefined}
      >
        <Icon src={Icons.ReplyArrow} size="100" />
      </IconButton>
      {canEdit && onEdit && (
        <IconButton
          onClick={onEdit}
          variant="SurfaceVariant"
          size="300"
          radii="300"
          aria-label="Edit"
          title="Edit"
        >
          <Icon src={Icons.Pencil} size="100" />
        </IconButton>
      )}
      {body && (
        <IconButton
          onClick={() => copyToClipboard(body)}
          variant="SurfaceVariant"
          size="300"
          radii="300"
          aria-label="Copy raw text"
          title="Copy raw text"
        >
          <Icon src={Icons.File} size="100" />
        </IconButton>
      )}
      {shiftHeld && canDelete && onDelete && (
        <IconButton
          onClick={onDelete}
          variant="Critical"
          size="300"
          radii="300"
          aria-label="Delete"
          title="Delete message (Shift held)"
        >
          <Icon src={Icons.Delete} size="100" />
        </IconButton>
      )}
      <PluginButtonSlot location="message-actions" />
      {menu && (
        <IconButton
          onClick={handleOpenMenu}
          variant="SurfaceVariant"
          size="300"
          radii="300"
          aria-label="Message menu"
          title="More actions"
        >
          <Icon src={Icons.VerticalDots} size="100" />
        </IconButton>
      )}
      </Box>
    </Menu>
  );
}
