import React, { Suspense, lazy } from 'react';
import { HEX_RE, normalizeHex } from '@wix/patterns-fields';
import { defineCellType } from '../../types';
import type { CellEditProps } from '../../types';
import { ColorView } from './View';

export { ColorView };

// Lazy-load the editor — it pulls in WSR's ColorPicker (≈10kb gzipped) which
// is only needed when the user actually edits a color cell. Splitting here
// (rather than inside CellColorInput) keeps the EditableTable main bundle
// free of ColorPicker and its transitive `color` lib + converter modules.
const LazyColorEdit = lazy(() =>
  import(/* webpackChunkName: "editable-table-color-edit" */ './Edit').then(
    (m) => ({ default: m.ColorEdit }),
  ),
);

const ColorEdit: React.FC<CellEditProps<string | undefined>> = (props) => (
  <Suspense fallback={null}>
    <LazyColorEdit {...props} />
  </Suspense>
);

export const colorCellType = defineCellType<string | undefined>({
  type: 'color',
  ViewComponent: ColorView,
  EditComponent: ColorEdit,
  serialize: (value) => value ?? '',
  deserialize: (raw) => (raw ? raw : undefined),
  validate: (value) => {
    if (!value) {
      return null;
    }
    return HEX_RE.test(value)
      ? null
      : 'Invalid color (expected #RGB or #RRGGBB)';
  },
  editable: true,
  clearable: true,
  // Unify empty representations (deserialize('') and clearable both produce
  // undefined) and accept hex pastes without the leading `#`.
  normalizeOnCommit: (value) =>
    value ? normalizeHex(value) ?? value : undefined,
  // Type-to-edit: clear the cell so the user types a fresh hex; CellColorInput's
  // controlled input then picks up subsequent keystrokes naturally.
  onTypeToEdit: () => ({ value: undefined }),
});
