import React from 'react';
import * as KB from './kanban-board';
import { IPageStore, PageStoreLoadData } from './store';
import { observer } from 'mobx-react-lite';
import * as TopRightMenuNs from '../misc-components/top-right-menu';
import { SetIssuesReadingTimestamp } from '../utils/unreaded-provider';
import axios from 'axios';
import * as ServiceActionsButtons from '../utils/service-actions-buttons';

export type Props = {
  store: IPageStore;
};

export const KanbanBoards = observer((props: Props) => {
  const data = props.store.data;
  if (!props.store.loaded || !data) {
    return <div>Loading...</div>;
  }
  const list: any[] = [];
  for (let i = 0; i < data.length; i++) {
    const boardData = data[i];
    const key = boardData.metainfo.title;
    const board = <KB.KanbanBoard store={boardData} key={key} />;
    list.push(board);
  }
  const topRightMenuStore = TopRightMenuNs.Store.create({ visible: false });
  const onAllReadClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    SetIssuesReadingTimestamp(props.store.issueIds);
    PageStoreLoadData(props.store);
  };
  let treeRefreshMenuItem: JSX.Element = <></>;
  if (props.store.canTreeRefresh) {
    const onTreeRefreshClick = (e: React.MouseEvent) => {
      if (e.target !== e.currentTarget) return;
      e.stopPropagation();
      axios.get(
        `${process.env.REACT_APP_BACKEND}simple-kanban-board/tree/${props.store.name}/refresh`,
      );
    };
    treeRefreshMenuItem = (
      <button onClick={onTreeRefreshClick}>Force tree refresh</button>
    );
  }
  return (
    <>
      <TopRightMenuNs.TopRightMenu store={topRightMenuStore}>
        <button onClick={onAllReadClick}>Всё прочитано</button>
        {treeRefreshMenuItem}
        <ServiceActionsButtons.IssuesForceRefreshButton />
        <ServiceActionsButtons.GetIssuesQueueSizeButton />
      </TopRightMenuNs.TopRightMenu>
      {list}
    </>
  );
});

export default KanbanBoards;
