import React from 'react';
import { ResponsiveWrapper } from 'app/shared/modules/chart/core';
import { DashboardChart } from 'app/modules/dashboard/components/dashboardChart';
import { DASHBOARD } from 'app/modules/dashboard/store/dashboard.constants';
import { useSelector } from 'react-redux';
import {
  createDashboardErrorStatusSelector,
  createDashboardIsLoadingSelector,
  getDashboardChartData,
} from 'app/modules/dashboard/store/dashboard.selectors';
import { isEmpty } from 'lodash';
import { ErrorsList } from 'app/shared/components/errorMessage/errorsList';
import { Spinner } from 'app/shared/components/spinner/spinner';

const DashboardChartWrapper = (props) => (
  <ResponsiveWrapper>
    {
      (size) => {
        const barSeries = useSelector(getDashboardChartData).barSeries;
        const dashboardFetchCollectionSelector = [ DASHBOARD.FETCH_KEY_FIGURES_SELECTOR ];

        const loadingStatus = useSelector(createDashboardIsLoadingSelector(dashboardFetchCollectionSelector));
        const errorLoadingStatus = useSelector(createDashboardErrorStatusSelector(dashboardFetchCollectionSelector));

        if (!isEmpty(errorLoadingStatus)) {
          return <ErrorsList errors={errorLoadingStatus} />;
        }

        if (loadingStatus) {
          return <Spinner />;
        }

        return !barSeries || barSeries.length === 0
          ? <div className="c-chart__no-data-label">No data available.</div>
          : <DashboardChart
            width={ size?.width }
            height={ size?.height }
            { ...props }
          />;
      }
    }
  </ResponsiveWrapper>
);

export { DashboardChartWrapper };
