import { observer } from 'mobx-react-lite';
import React from 'react';
import * as DashboardStoreNs from './dashboard-store';
import * as TopRightMenuNs from '../misc-components/top-right-menu';
import * as WidgetNs from './widget';
import * as EditorNs from './editor';

export type Props = { store: DashboardStoreNs.IDashboard };

export const Dashboard = observer((props: Props): JSX.Element => {
  if (!props.store.loaded) {
    console.debug('Dashboard - store:', JSON.stringify(props.store)); // DEBUG
    return <pre>Loading... {JSON.stringify(props.store)}</pre>;
  }

  const topRightMenuStore = TopRightMenuNs.Store.create({ visible: false });

  const widgets = props.store.data?.widgets.map((widget) => {
    widget.setDashboardId(props.store.id);
    return <WidgetNs.Widget key={widget.id} store={widget}></WidgetNs.Widget>;
  });

  const editorStore = EditorNs.Store.create({ dashboardId: props.store.id });
  const onEditClick = (e: React.MouseEvent) => {
    if (e.target !== e.currentTarget) return;
    e.stopPropagation();
    editorStore.show();
  };

  const res = (
    <div>
      <EditorNs.Editor store={editorStore}></EditorNs.Editor>
      <TopRightMenuNs.TopRightMenu store={topRightMenuStore}>
        <a href="/dashboards">Назад</a>
        <span>Дашборд - {props.store.data?.title || props.store.id}</span>
        <button onClick={onEditClick}>edit</button>
      </TopRightMenuNs.TopRightMenu>
      {widgets}
    </div>
  );

  return res;
});
