// This is an adapter to implement the same server-side-rendered 'points' view
// that is seen on the monitor page, implemented as 'PointTableView' in
// DataTable.tsx.
// It might make sense in the future to replace the maintenance and warning
// tables on the stats page with a modified version of <DataTable>,
// but for now, this is a quick way to revise just that points view to be
// consistent with the monitor page.
// @author Ann Yanich

import React, { useEffect, useState } from 'react';
import { fetchPointsTable } from '../../requests';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
// import { FixTableLayout } from '~t/DataPage/DataTable';
import { FixTableLayout } from '~t/share/aufgaben-shared/components/FixTableLayout'; //CMS-Prototype

type StatsPointsViewProps = {
  ergId: string;
};

// Represents the server-side-rendered points table for a given Erg
type StatsPointsViewState =
  | {
      tag: 'loaded';
      html: string;
    }
  | {
      tag: 'loading';
    }
  | {
      tag: 'error';
      error: string;
    };

const StatsPointsView: React.FC<StatsPointsViewProps> = (props) => {
  const [state, setState] = useState<StatsPointsViewState>({ tag: 'loading' });
  // On mount, send a request to fetch the points table from the server
  useEffect(() => {
    fetchPointsTable(props.ergId)
      .then((res) => {
        const html = res.data;
        setState({
          tag: 'loaded',
          html,
        });
      })
      .catch((error) => {
        setState({
          tag: 'error',
          error: error.toString(),
        });
      });
  }, []);

  let content: JSX.Element;
  if (state.tag === 'loading') {
    content = <div>Loading</div>;
  } else if (state.tag === 'error') {
    content = <div>Error: {state.error}</div>;
  } else {
    content = <div dangerouslySetInnerHTML={{ __html: state.html }}></div>;
  }
  return (
    <Paper>
      <Box p={1}>
        <FixTableLayout>{content}</FixTableLayout>
      </Box>
    </Paper>
  );
};

export default StatsPointsView;
