import React from 'react';
import { Loader } from '@wix/design-system';

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

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

const LazyRichTextEdit = React.lazy(() =>
  import(/* webpackChunkName: "EditableTableRichTextEdit" */ './Edit').then(
    (m) => ({ default: m.RichTextEdit }),
  ),
);

const RichTextEdit = (props: CellEditProps<string>) => (
  <React.Suspense fallback={<Loader size="tiny" />}>
    <LazyRichTextEdit {...props} />
  </React.Suspense>
);

export const richTextCellType = defineCellType<string>({
  type: 'richText',
  ViewComponent: RichTextView,
  EditComponent: RichTextEdit,

  /** Serialize to single-line plain text for TSV clipboard. */
  serialize: (value) => {
    if (!value) return '';
    return HTMLToText(value, { singleLine: true }).trim();
  },

  /** Deserialize a pasted plain-text string back to a minimal HTML paragraph. */
  deserialize: (raw) => (raw ? `<p>${raw}</p>` : ''),

  editable: true,
  clearable: false,

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