import { LoadingStatus } from 'client/common/loadingStatus';
import Result from 'client/Components/Result';
import Spinner from 'client/Components/Spinner';
import Modal from 'client/Elements/Modal';
import withModal from 'client/hocs/Calculation/withModal';
import { Flex } from 'client/UIKit/grid';
import React, { useEffect, useState } from 'react';
import Info from './Info';
import fetchData from './lib/fetchData';
import Results from './Results';
import ResultsTable from './ResultsTable';
import Sections from './Sections';

const Calculation = () => {
  const [status, setStatus] = useState(LoadingStatus.loading);
  useEffect(() => {
    fetchData()
      .then(() => {
        setStatus(LoadingStatus.ready);
      })
      .catch(() => {
        setStatus(LoadingStatus.error);
      });
  }, []);

  if (status === LoadingStatus.loading) {
    return <Spinner />;
  }

  if (status === LoadingStatus.error) {
    const ServerError = Result[500];
    return <ServerError />;
  }

  const ModalComponent = withModal(Modal);

  return (
    <Flex
      mx={[0, 0, 0, 0, '7%']}
      mb="50px"
      flexWrap={['wrap', 'wrap', 'wrap', 'nowrap']}
      justifyContent="center"
      minHeight="800px"
    >
      <Sections
        width={['100vw', '100vw', '100vw', '700px', '850px', '1000px']}
      />
      <Flex
        flexDirection={[
          'column',
          'column',
          'column',
          'column',
          'column',
          'row',
        ]}
      >
        <Flex
          flexDirection="column"
          minWidth={['100vw', '100vw', '100vw', '450px']}
          maxWidth={[undefined, undefined, undefined, '450px']}
        >
          <Info />
          <Results />
        </Flex>
        <ResultsTable
          minHeight="500px"
          width={['100vw', '100vw', '100vw', '540px']}
        />
      </Flex>
      <ModalComponent />
    </Flex>
  );
};

export default Calculation;
