import React, { useEffect, useState } from "react";
import { LineChart } from "../components";
import {
  ChartDataQueryVariables,
  useChartDataQuery,
} from "../generated/graphql";
import { useCurrentSiteInfo } from "../hooks";

interface ChartProps {
  input: ChartDataQueryVariables["input"];
}

export const Chart: React.FC<ChartProps> = (props) => {
  const currentSiteInfo = useCurrentSiteInfo();
  const chartDataQueryResults = useChartDataQuery({
    variables: {
      input: {
        siteId: currentSiteInfo.data.nocodelyticsId,
        ...props.input,
      },
    },
    skip: !currentSiteInfo.data.nocodelyticsId,
  });

  const loading: boolean =
    chartDataQueryResults.loading || currentSiteInfo.loading;
  const error: string | undefined =
    chartDataQueryResults.error?.message || currentSiteInfo.error;
  const data = chartDataQueryResults.data;
  if (loading) {
    return <div>Loading</div>;
  }
  if (error) {
    return <div style={{ color: "red" }}>{error}</div>;
  }
  if (!data?.chartData) {
    return <div>No data</div>;
  }
  const total = data?.chartData.data[0].values.reduce(
    (acc, item) => acc + item.value,
    0
  );
  return (
    <div>
      <div style={{ height: 175, width: "100%" }}>
        <LineChart
          title={`${props.input.metricType} (${total})`}
          data={data?.chartData.data[0].values.reduce(
            (acc, item) => {
              acc.labels.push(new Date(Date.parse(item.label)));
              acc.values.push(item.value);
              return acc;
            },
            { labels: [], values: [] }
          )}
        />
      </div>
    </div>
  );
};
