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

import {
  Popover,
  PopoverAnchor,
  PopoverContent,
} from '@/components/plate-ui/popover';

import { AttachmentToolbar } from './attachment-toolbar';

export interface AttachmentPopoverProps {
  pluginkey?: string;
  elementRef?: React.RefObject<HTMLElement>;
  children: React.ReactNode;
  align?: 'left' | 'center' | 'right' | 'justify';
}

export function AttachmentPopover({
  pluginkey,
  elementRef,
  children,
  align,
}: AttachmentPopoverProps) {
  const readOnly = useReadOnly();
  const selected = useSelected();

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

  const formatAlign = useMemo(() => {
    if (align === 'left') return 'start';
    if (align === 'center') return 'center';
    if (align === 'right') return 'end';
    return 'start';
  }, [align]);

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

  return (
    <Popover open={isOpen} modal={false}>
      <PopoverAnchor>{children}</PopoverAnchor>
      <PopoverContent
        className="w-auto p-1"
        align={formatAlign}
        onOpenAutoFocus={(e) => e.preventDefault()}
      >
        <AttachmentToolbar pluginkey={pluginkey} elementRef={elementRef} />
      </PopoverContent>
    </Popover>
  );
}
