import React from 'react';
import { Loader } from '@wix/design-system';
import { RicosDocument } from '@wix/ricos';
import { fromPlainText, toPlainTextSync } from '@wix/ricos/content';

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

const richContentEditFactory = () =>
  import(/* webpackChunkName: "EditableTableRichContentEdit" */ './Edit');

if (typeof process !== 'undefined' && process.env.STORYBOOK_VISUAL_E2E !== 'true') {
  richContentEditFactory();
}

const LazyRichContentEdit = React.lazy(richContentEditFactory);

const RichContentEdit = (props: CellEditProps<unknown>) => (
  <React.Suspense fallback={<Loader size="tiny" />}>
    <LazyRichContentEdit {...props} />
  </React.Suspense>
);

export const richContentCellType = defineCellType<unknown>({
  type: 'richContent',
  ViewComponent: RichContentView,
  EditComponent: RichContentEdit,

  /** Serialize to single-line plain text for TSV clipboard. */
  serialize: (value) => {
    if (!value) {
      return '';
    }
    return typeof value === 'string'
      ? value
      : toPlainTextSync(value as RicosDocument, {
          delimiter: ' ',
        });
  },

  /** Deserialize a pasted plain-text string back to a minimal Ricos document. */
  deserialize: (raw) => (raw ? fromPlainText(raw) : null),

  editable: true,
  clearable: false,

  onTypeToEdit: () => ({}),
});
