import React from 'react';
import { DashboardsList } from './dashboards-list';
import * as Store from './dashboards-store';

export const DashboardsPage = (): JSX.Element => {
  const store = Store.List.create({ loaded: false, list: [] });
  Store.ListStoreLoadData(store);

  const onNewDashboardButtonClick = async (e: React.MouseEvent) => {
    if (e.target !== e.currentTarget) return;
    e.stopPropagation();
    const createUrl = `${process.env.REACT_APP_BACKEND}api/dashboard`;
    const createResp = await fetch(createUrl, {
      method: 'POST',
    });
    if (!createResp || !createResp.ok) {
      alert(`Ошибка - Не удалось создать новый дашборд`);
      return;
    }
    const dashboardId = await createResp.text();
    const dashboardName = prompt(
      `Dashboard name for dashboardId = ${dashboardId}`,
    );
    if (dashboardName) {
      const modifyUrl = `${process.env.REACT_APP_BACKEND}api/dashboard/${dashboardId}`;
      const modifyResp = await fetch(modifyUrl, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ widgets: [], title: dashboardName }),
      });
      if (!modifyResp || !modifyResp.ok) {
        alert(`Не удалось выполнить создание дашборда`);
      } else {
        alert(`Создан дашборд ${dashboardName}`);
      }
      return;
    } else {
      alert(`Создан анонимный дашборд ${dashboardId}`);
      return;
    }
  };

  return (
    <>
      <button onClick={onNewDashboardButtonClick}>New dashboard</button>
      <DashboardsList store={store} />
    </>
  );
};
