import React, { useRef, useState, useEffect } from 'react';
import { APP_MODE } from '../../models/app';
import { CANVAS_EVENT } from '../../models/canvas';
import Layout from '../Layout';
import ComponentView from '../Component';
import { useForceUpdate } from '../hooks';
import { getPrefixedClassName } from '../utils';
import { CanvasProps } from './types';

export default function Canvas(props: CanvasProps) {
  const { canvas, appMode } = props;
  const canvasRef = useRef<HTMLDivElement>();
  const [didComponentMount, setDidComponentMount] = useState<boolean>(false);
  const forceUpdate = useForceUpdate();

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

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

  useEffect(() => {
    if (canvasRef.current) {
      setDidComponentMount(true);
    }
  }, [canvasRef]);

  useEffect(() => {
    // Get dataset after Components are mounted and listen to COMPONENT_EVENT.GetDataset
    if (didComponentMount) canvas.getAllDataset();
  }, [didComponentMount]);

  const handleComponentClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>, componentId: string) => {
    canvas.focusComponent(componentId);
    e.stopPropagation();
  };

  return (
    <div className={getPrefixedClassName('canvas')} ref={canvasRef}>
      <Layout layouts={canvas.layouts} resizable={appMode === APP_MODE.edit} draggable={appMode === APP_MODE.edit}>
        {canvas.components.map((component) => {
          const {
            config: { id },
          } = component;
          return (
            <div
              key={id}
              className={getPrefixedClassName('component-view-container')}
              onClick={(e) => handleComponentClick(e, id)}
            >
              <ComponentView key={id} component={component} />
            </div>
          );
        })}
      </Layout>
    </div>
  );
}
