import React, { useMemo } from "react";

import { Stack, Typography } from "@mui/material";

import Chart from "../../../components/Chart";
import WidgetCard from "../../../components/WidgetCard";
import { useApi } from "../../../contexts/ApiContext";
import { useDashboardFilter } from "../../../contexts/DashboardFilterContext";
import { useI18n } from "../../../contexts/I18nContext";
import { useUser } from "../../../contexts/UserContext";
import { ContribComponent } from "../../../types";
import {
  granularityLabel,
  pluralizeGranularity,
  PurchaseCountItem,
} from "../../../types/dashboard";
import { hasPermission } from "../../../util/has_permission";
import { diffDatesByGranularityWithFilter } from "../utils/diffDatesByGranularity";

const PurchaseCountWidget: ContribComponent<PurchaseCountItem[]> = ({ data: initialData, sx }) => {
  const { filter } = useDashboardFilter();
  const data = initialData;
  const { t } = useI18n();
  const api = useApi();
  const { user } = useUser();

  const filteredAmount = useMemo(() => {
    return diffDatesByGranularityWithFilter(filter);
  }, [filter]);

  const totalPurchases = useMemo(() => {
    return data.reduce((acc, { count }) => acc + count, 0);
  }, [data]);

  const averagePurchases = useMemo(() => {
    let average = totalPurchases / filteredAmount;
    if (Number.isNaN(average)) average = 0;

    const fixed = average.toFixed(1);
    return Number.parseFloat(fixed).toString();
  }, [totalPurchases, filteredAmount]);

  const isFourColumn = useMemo(() => {
    // Ugly check to see if the "Total Subscription Count" widget is present
    if (
      "subscription.stats:total" in api.operations &&
      "dashboard:stats:subscription:total" in api.contrib
    ) {
      const [{ component }] = Object.values(api.contrib["dashboard:stats:subscription:count"]);

      if (component != null) {
        return hasPermission(user, component.permission);
      }
    }

    return false;
  }, [api, user]);

  return (
    <>
      <WidgetCard
        gridColumn={{ md: "span 6", sm: "span 1" }}
        gridRow="span 2"
        sx={sx}
        title={t(`${granularityLabel(filter.granularity)} Purchases`)}
      >
        <Chart
          charts={["bar", "area"]}
          csvFileName="purchase_count"
          data={data.map((item) => ({ ...item }))}
          dataKeyX="date"
          dataKeyY="count"
          dataTable={true}
        />
      </WidgetCard>

      <WidgetCard
        gridColumn={{ md: isFourColumn ? "span 3" : "span 4", sm: "span 1" }}
        gridRow="span 1"
        sx={sx}
        title={t("Purchase Count")}
      >
        <Stack direction={"column"} height={"100%"} px={2}>
          <Stack borderBottom="1px solid" borderColor="divider" height="100%">
            <Typography component="p" fontSize={28} fontWeight={700} variant="h5">
              {totalPurchases.toLocaleString()}
            </Typography>
          </Stack>

          <Typography color="textSecondary" variant="overline">
            {t(`Over ${pluralizeGranularity(filteredAmount, filter.granularity)}`)}
          </Typography>
        </Stack>
      </WidgetCard>

      <WidgetCard
        gridColumn={{ md: isFourColumn ? "span 3" : "span 4", sm: "span 1" }}
        gridRow="span 1"
        sx={sx}
        title={t("Purchase Average")}
      >
        <Stack height="100%" px={2}>
          <Stack borderBottom="1px solid" borderColor="divider" height="100%">
            <Stack alignItems="baseline" direction="row" flexWrap="wrap" gap={1}>
              <Typography component="p" fontSize={28} fontWeight={700} variant="h5">
                {averagePurchases}
              </Typography>
              <Typography color="textSecondary" fontSize={18} pb={1} textTransform={"uppercase"}>
                /&nbsp;{filter.granularity}
              </Typography>
            </Stack>
          </Stack>

          <Typography color="textSecondary" variant="overline">
            {t(`Over ${pluralizeGranularity(filteredAmount, filter.granularity)}`)}
          </Typography>
        </Stack>
      </WidgetCard>
    </>
  );
};

export default PurchaseCountWidget;
