import React from 'react';
import { Loader } from '@wix/design-system';
import type { Address } from '@wix/patterns-fields';
import type { CellEditProps } from '../../types';
import { defineCellType } from '../../types';
import { AddressCellView } from './View';

const addressEditFactory = () =>
  import(/* webpackChunkName: "EditableTableAddressEdit" */ './Edit').then(
    (m) => ({ default: m.AddressEdit }),
  );

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

const LazyAddressEdit = React.lazy(addressEditFactory);

const AddressEdit = (props: CellEditProps<Address | undefined>) => (
  <React.Suspense fallback={<Loader size="tiny" />}>
    <LazyAddressEdit {...props} />
  </React.Suspense>
);

export { AddressCellView };
export type { AddressCellTypeConfig } from './Edit';

export const addressCellType = defineCellType<Address | undefined>({
  type: 'address',
  ViewComponent: AddressCellView,
  EditComponent: AddressEdit,
  serialize: (value) => (value ? JSON.stringify(value) : ''),
  deserialize: (raw) => {
    if (!raw) {
      return undefined;
    }
    try {
      const parsed = JSON.parse(raw);
      if (parsed && typeof parsed.formatted === 'string') {
        return parsed as Address;
      }
    } catch {}
    return undefined;
  },
  validate: (value) => {
    if (!value) {
      return null;
    }
    if (
      typeof value === 'object' &&
      typeof value.formatted === 'string' &&
      value.formatted.length > 0
    ) {
      return null;
    }
    return 'Invalid address';
  },
  editable: true,
  clearable: true,
  // Type-to-edit clears the cell so the user starts a fresh search query.
  onTypeToEdit: () => ({ value: undefined }),
});
