import React, { useEffect, useState } from 'react';
import {
  createPrimitiveComponent,
  isCollapsed,
  setNodes,
  useEditorRef,
  useHotkeys,
} from '@udecode/plate-common';

import { SizeLength } from '../../utils';
import { TAttachmentElement } from '../types';
import { useAttachmentState } from '../useAttachmentState';

export const useFloatingMediaWidthEditInputState = () => {
  const editor = useEditorRef();
  const { width } = useAttachmentState().element;

  useHotkeys(
    'enter',
    (e: any) => {
      setNodes<TAttachmentElement>(editor, {
        width: e.target.value,
        height: '',
      });
    },
    {
      enableOnFormTags: ['INPUT'],
    },
    []
  );
  if (!isCollapsed(editor.selection)) return {};

  const widthValue = typeof width === 'number' ? `${width}px` : width;

  return {
    value: widthValue,
    defaultValue: widthValue,
  };
};

export const useFloatingMediaWidthEditInput = ({
  value,
  defaultValue,
}: ReturnType<typeof useFloatingMediaWidthEditInputState>) => {
  const [inputValue, setInputValue] = useState<SizeLength>('');

  const onChange: React.ChangeEventHandler<HTMLInputElement> =
    React.useCallback((e) => {
      setInputValue(e.target.value);
    }, []);

  useEffect(() => {
    setInputValue(value || '');
  }, [value]);

  return {
    props: {
      value: inputValue,
      defaultValue,
      onChange,
    },
  };
};

export const FloatingMediaWidthEditInput = createPrimitiveComponent('input')({
  stateHook: useFloatingMediaWidthEditInputState,
  propsHook: useFloatingMediaWidthEditInput,
});
