import { useEffect, useState } from 'react';
import { Spin } from 'antd';
import { COMPONENT_EVENT, COMPONENT_MODE, QueryDatasetStatus, GET_DATASET_STATUS } from '../../models/component';
import { useForceUpdate } from '../hooks';
import { getPrefixedClassName } from '../utils';
import { ComponentProps } from './types';

export default function Component(props: ComponentProps) {
  const { component } = props;
  const {
    config: { id, config },
    dataset,
  } = component;
  const ComponentView = component.componentPlugin?.View;
  const [loading, setLoading] = useState<boolean>(false);
  const forceUpdate = useForceUpdate();

  useEffect(() => {
    component.on(COMPONENT_EVENT.GetDataset, (status: QueryDatasetStatus) => {
      if (status === GET_DATASET_STATUS.loading) setLoading(true);
      if (status === GET_DATASET_STATUS.success) setLoading(false);
    });
    component.on(COMPONENT_EVENT.Focus, forceUpdate);
    component.on(COMPONENT_EVENT.Blur, forceUpdate);
    component.on(COMPONENT_EVENT.UpdateConfigPanel, forceUpdate);

    return () => {
      component.off(COMPONENT_EVENT.GetDataset);
      component.off(COMPONENT_EVENT.Focus);
      component.off(COMPONENT_EVENT.Blur);
      component.off(COMPONENT_EVENT.UpdateConfigPanel);
    };
  }, []);

  return (
    <div
      className={`${getPrefixedClassName('component-view')} ${
        component.mode === COMPONENT_MODE.focus ? getPrefixedClassName('component-view-focus') : ''
      }`}
    >
      {dataset ? (
        !!ComponentView && (
          <Spin wrapperClassName={getPrefixedClassName('spin')} spinning={loading}>
            {!!dataset && <ComponentView id={id} data={dataset} config={config} />}
          </Spin>
        )
      ) : (
        <span className={getPrefixedClassName('component-view-placeholder')}>Please select a dataset</span>
      )}
    </div>
  );
}
