import React, { useEffect } from 'react';
import dayjs from 'dayjs';
import { useQuery } from '@apollo/client';
import {
  EmptyState,
  ChartStateLoading as Loading,
  ChartCard,
  ChartTitle,
  ChartHeader,
  Container,
} from '../index';

const GraphQLWrapper = ({ graphQlProps, ...props }) => {
  const {
    dataParser = data => ({
      metrics: data,
    }),
    query,
    save = () => {},
    variables,
    title,
  } = graphQlProps;

  const fetchPolicy = process.env.NODE_ENV === 'test' ? 'no-cache' : undefined;
  const { data, error, loading } = useQuery(query, {
    fetchPolicy,
    variables,
  });

  useEffect(() => {
    if (data) {
      save(data);
    }
  }, [data]);

  if (error) {
    // TODO push this into bugsnag
    console.log(error);
    return (
      <ChartCard>
        <EmptyState
          header="There was a problem loading the data"
          description="If this persists, please contact us"
        />
      </ChartCard>
    );
  } else if (data && graphQlProps.content) {
    props = {
      ...props,
      ...dataParser(data),
      loading,
    };

    return (
      <React.Fragment>{<graphQlProps.content {...props} />}</React.Fragment>
    );
  }

  if (props.forReport) {
    return <Loading active noBorder />;
  }

  return (
    <ChartCard>
      {title && (
        <ChartHeader>
          <ChartTitle>{title}</ChartTitle>
        </ChartHeader>
      )}
      <Container>
        <Loading active noBorder />
      </Container>
    </ChartCard>
  );
};

export function formatQueryVariables(profile, variables) {
  return {
    serviceId: profile.serviceId,
    serviceType: profile.service,
    ...variables,
    endDate: dayjs(variables.endDate, 'MM-DD-YYYY').format('YYYY-MM-DD'),
    startDate: dayjs(variables.startDate, 'MM-DD-YYYY').format('YYYY-MM-DD'),
  };
}

export default GraphQLWrapper;
