import { useEffect } from 'react';
import { useForceUpdate } from '../hooks';
import { getPrefixedClassName } from '../utils';
import Layout from '../Layout';
import DatasetManager from '../DatasetManager';
import ComponentMenu from '../ComponentMenu';
import Canvas from '../Canvas';
import ConfigPanel from '../ConfigPanel';
import { CANVAS_EVENT } from '../../models/canvas';
import { AppProps } from './types';

export default function App(props: AppProps) {
  const {
    app: {
      config: { panel },
      layouts,
      datasetManager,
      canvas,
      mode,
    },
  } = props;

  const forceUpdate = useForceUpdate();

  useEffect(() => {
    canvas.on(CANVAS_EVENT.AddComponent, forceUpdate);

    return () => {
      canvas.off(CANVAS_EVENT.AddComponent);
    };
  }, []);

  return (
    <div className={`${getPrefixedClassName('app')}`}>
      <Layout layouts={layouts} resizable={false} draggable={false} margin={[4, 4]}>
        {panel['dataset-manager'].enabled && (
          <div
            key="dataset-manager"
            className={`${getPrefixedClassName('dataset-container')} ${getPrefixedClassName('panel')}`}
          >
            <DatasetManager datasetManager={datasetManager} canvas={canvas} />
          </div>
        )}
        {panel['component-menu'].enabled && (
          <div
            key="component-menu"
            className={`${getPrefixedClassName('component-menu-container')} ${getPrefixedClassName('panel')}`}
          >
            <ComponentMenu canvas={canvas} />
          </div>
        )}
        {panel.canvas.enabled && (
          <div
            key="canvas"
            className={`${getPrefixedClassName('canvas-container')} ${getPrefixedClassName('panel')}`}
            onClick={() => canvas.blurComponent()}
          >
            <Canvas canvas={canvas} appMode={mode} />
          </div>
        )}
        {panel['config-panel'].enabled && (
          <div
            key="config-panel"
            className={`${getPrefixedClassName('config-panel-container')} ${getPrefixedClassName('panel')}`}
          >
            <ConfigPanel canvas={canvas} />
          </div>
        )}
      </Layout>
    </div>
  );
}
