import React, { useRef } 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 { inputVariants } from '@/components/plate-ui/input';
import {
  Popover,
  PopoverAnchor,
  PopoverContent,
} from '@/components/plate-ui/popover';
import { Separator } from '@/components/plate-ui/separator';

import { useLayoutState } from '../layout-store';

export interface LayoutToolbarPopoverProps {}

export function LayoutToolbarPopover({
  children,
}: React.PropsWithChildren<LayoutToolbarPopoverProps>) {
  const readOnly = useReadOnly();
  const selected = useSelected();
  const inputRef = useRef<HTMLInputElement>(null);

  const {
    element,
    layoutElement,
    insertLeft,
    insertRight,
    setDynamicChildWidth,
  } = useLayoutState();

  const { width } = element;

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

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

  const onInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key !== 'Enter') return;
    const value = inputRef.current?.value || '';
    if (!setDynamicChildWidth(value)) {
      inputRef.current?.value == width;
    }
  };

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

  return (
    <Popover open={isOpen} modal={false}>
      <PopoverAnchor>{children}</PopoverAnchor>
      <PopoverContent
        align="center"
        side="top"
        sideOffset={10}
        className="w-auto p-1"
        onOpenAutoFocus={(e) => e.preventDefault()}
      >
        <div className="box-content flex h-9 items-center gap-1">
          <Button variant="ghost" size="sms" onClick={insertLeft}>
            <Icons.panelLeftClose
              className={iconVariants({ variant: 'toolbar' })}
            />
          </Button>
          <Button variant="ghost" size="sms" onClick={insertRight}>
            <Icons.panelRightClose
              className={iconVariants({ variant: 'toolbar' })}
            />
          </Button>
          {layoutElement.children.length > 1 && (
            <input
              ref={inputRef}
              defaultValue={width}
              onKeyDown={onInputKeyDown}
              className={inputVariants({ variant: 'normal', w: 'sm', h: 'sm' })}
            />
          )}
          <Separator orientation="vertical" className="my-1" />
          <Button variant="ghost" size="sms" {...buttonProps}>
            <Icons.delete className={iconVariants({ variant: 'toolbar' })} />
          </Button>
        </div>
      </PopoverContent>
    </Popover>
  );
}
