import React from 'react';
import { Loader } from '@wix/design-system';
import type { WixCodeGalleryItem } from '@wix/patterns-fields/auto-field-types';
import { defineCellType } from '../../types';
import type { CellEditProps } from '../../types';
import { MediaGalleryView } from './View';

const mediaGalleryEditFactory = () =>
  import(/* webpackChunkName: "EditableTableMediaGalleryEdit" */ './Edit');

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

const LazyMediaGalleryEdit = React.lazy(mediaGalleryEditFactory);

const MediaGalleryEdit = (
  props: CellEditProps<WixCodeGalleryItem[] | null>,
) => (
  <React.Suspense fallback={<Loader size="tiny" />}>
    <LazyMediaGalleryEdit {...props} />
  </React.Suspense>
);

export const mediaGalleryCellType = defineCellType<WixCodeGalleryItem[] | null>(
  {
    type: 'mediaGallery',
    ViewComponent: MediaGalleryView,
    EditComponent: MediaGalleryEdit,
    serialize: (value) => (value ?? []).map((item) => item.src).join(', '),
    clearable: true,
    showEditWhenFocused: true,
    // Returning undefined blocks all key presses from starting type-to-edit, but
    // the presence of the function sets the :typeToEdit CSS modifier which keeps
    // the selection borders visible while the cell is in edit mode (double border).
    onTypeToEdit: () => undefined,
  },
);
