import { useLazyModules } from '@websolutespa/bom-mixer-hooks';
import { ILazyComponent, ILazyModules } from '@websolutespa/bom-mixer-models';
import React from 'react';
import { Skeleton } from '../../components';
import { LAZY_MODULES } from '../lazy';

export type LazyLoaderProps = {
  components?: ILazyComponent[],
  modules?: ILazyModules,
  initialIndex?: number;
};

const lazyLoadComponent = (component: ILazyComponent, modules: ILazyModules, index: number = 0): React.JSX.Element => {
  const key = (component.blockType || component.schema || 'unkown_type') as keyof typeof modules;
  const Component = modules[key] || modules['not-found' as keyof typeof modules];
  return (<Component item={component} index={index} />);
};

export const LazyLoader = ({ components, modules, initialIndex = 0 }: LazyLoaderProps) => {
  const lazyModules = useLazyModules();
  if (!components) {
    return null;
  }
  const subModules = modules || { ...LAZY_MODULES, ...lazyModules };
  return (
    <>
      {components.map((component, index: number) => (
        <React.Suspense key={index} fallback={(
          <Skeleton minHeight="50vh" />
        )}>
          {lazyLoadComponent(component, subModules, initialIndex + index)}
        </React.Suspense>
      ))}
    </>
  );
};
