import React from 'react';

import { CellRichTextInput } from '@wix/patterns-fields';

import type { RichTextCellTypeConfig } from '../../../../state/EditableTable/types';
import type { CellEditProps } from '../../types';
import { RichTextView } from './View';

export const RichTextEdit: React.FC<CellEditProps<string>> = ({
  value,
  onChange,
  onCommit,
  editTrigger,
  typeConfig,
  columnId,
  rowKey,
}) => {
  const initialTypedKey =
    editTrigger &&
    typeof editTrigger === 'object' &&
    editTrigger.kind === 'type'
      ? editTrigger.key
      : undefined;

  const { textStyle } =
    (typeConfig as RichTextCellTypeConfig | undefined) ?? {};

  return (
    <>
      {/* Show plain-text view underneath while the popover is open */}
      <RichTextView value={value} columnId={columnId} rowKey={rowKey} />
      <CellRichTextInput
        value={value}
        onChange={onChange}
        initialTypedKey={initialTypedKey}
        onCommit={onCommit}
        textStyle={textStyle}
      />
    </>
  );
};
