import React from 'react';
import {
  isSelectionExpanded,
  useEditorSelector,
  useRemoveNodeButton,
} from '@udecode/plate-common';
import { useReadOnly, useSelected } from 'slate-react';

import { Icons, iconVariants } from '@/components/icons';
import { Button } from '@/components/plate-ui/button';
import {
  Popover,
  PopoverAnchor,
  PopoverContent,
} from '@/components/plate-ui/popover';
import { Separator } from '@/components/plate-ui/separator';

import { useHighlightState } from '../highlight-block-store';
import { ColorDropdownMenu } from './color-dropdown-menu';

export interface HighLightPopoverProps {
  children: React.ReactNode;
  align?: 'left' | 'center' | 'right' | 'justify';
}

export function HighLightPopover({ children }: HighLightPopoverProps) {
  const readOnly = useReadOnly();
  const selected = useSelected();

  const { element, setHighlightState } = useHighlightState();

  const { props: buttonProps } = useRemoveNodeButton({ element });

  const selectionCollapsed = useEditorSelector(
    (editor) => !isSelectionExpanded(editor),
    []
  );
  const isOpen = !readOnly && selected && selectionCollapsed;

  const toggleShowEmoji = () => {
    setHighlightState({ showEmoji: !element.showEmoji });
  };

  if (readOnly) return <>{children}</>;

  return (
    <Popover open={isOpen} modal={false}>
      <PopoverAnchor>{children}</PopoverAnchor>
      <PopoverContent
        align="center"
        side="top"
        className="w-auto p-1"
        onOpenAutoFocus={(e) => e.preventDefault()}
      >
        <div className="box-content flex h-9 items-center gap-1">
          {element.showEmoji ? (
            <Button variant="ghost" size="sms" onClick={toggleShowEmoji}>
              <Icons.emojiShow
                className={iconVariants({ variant: 'toolbar' })}
              />
            </Button>
          ) : (
            <Button variant="ghost" size="sms" onClick={toggleShowEmoji}>
              <Icons.emojiHidden
                className={iconVariants({ variant: 'toolbar' })}
              />
            </Button>
          )}
          <Separator orientation="vertical" className="my-1" />
          <ColorDropdownMenu>
            <Icons.colorPickPan
              className={iconVariants({ variant: 'toolbar' })}
            />
          </ColorDropdownMenu>
          <Separator orientation="vertical" className="my-1" />
          <Button variant="ghost" size="sms" {...buttonProps}>
            <Icons.delete className={iconVariants({ variant: 'toolbar' })} />
          </Button>
        </div>
      </PopoverContent>
    </Popover>
  );
}
