import React, { useCallback } from 'react';

import type { RichContent } from '@wix/ricos';
import { CellRichContentInput } from '@wix/patterns-fields/cell-rich-content-input';

import type { CellEditProps } from '../../types';
import { RichContentView } from './View';

export const RichContentEdit: React.FC<CellEditProps<unknown>> = ({
  value,
  onChange,
  onCommit,
  // onCancel intentionally unused: Escape commits via RichContentEditor.onClose -> editorRef.prePublish().
  editTrigger,
  columnId,
  rowKey,
}) => {
  const initialTypedKey =
    editTrigger &&
    typeof editTrigger === 'object' &&
    editTrigger.kind === 'type'
      ? editTrigger.key
      : undefined;

  const handleSave = useCallback(() => {
    onCommit();
  }, [onCommit]);

  return (
    <>
      {/* Show cell view underneath while the modal is open */}
      <RichContentView value={value} columnId={columnId} rowKey={rowKey} />
      <CellRichContentInput
        value={value}
        onChange={onChange as (v: RichContent | undefined) => void}
        onSave={handleSave}
        initialTypedKey={initialTypedKey}
      />
    </>
  );
};

export default RichContentEdit;
