import * as React from 'react';
import { useCallback } from 'react';
import { emitCustomEvent } from '../../customEventTrigger';
import { HotAreas } from '../../HotAreas';
import { componentNodeMap, getComponentNode } from '../../componentNodeMap';
import { onComponentEventAction } from '../../componentEventActionEmitter';

export function ReactAdaptor({ instance, injectProps = {}, meta, global }) {
  const { component, data, style, commonStyle, key } = instance;

  const View = React.useMemo(() => instance.component.component, []);
  const hotAreas = React.useMemo(() => {
    return component.__implementHotArea ? (
      <HotAreas global={global} meta={meta} instance={instance} />
    ) : null;
  }, []);

  const emit = useCallback(trigger => emitCustomEvent(instance, trigger, global, meta), [
    instance,
    global,
    meta,
  ]);
  const on = useCallback(
    (eventName, callback) => onComponentEventAction(instance, eventName, callback),
    [instance]
  );

  if (!View) {
    console.error(`Cannot find component [${component.name}] by id [${component.id}]`);
    return null;
  }

  return (
    <View
      key={key}
      componentKey={key}
      data={data}
      style={style}
      commonStyle={commonStyle}
      global={global}
      meta={meta}
      emit={emit}
      on={on}
      hotAreas={hotAreas}
      componentsMap={componentNodeMap}
      getComponentByKey={getComponentNode}
      {...injectProps}
    />
  );
}
