import React, { useMemo, useState } from "react";

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

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 { pluralizeGranularity, PurchaseAmountItem } from "../../../types/dashboard";
import { hasPermission } from "../../../util/has_permission";
import ExchangeSwitch from "../components/ExchangeSwitch";
import SitesAmountsList from "../components/SitesAmountsList";
import SitesTotal from "../components/SitesTotal";
import { useExchangedData } from "../hooks/useExchangedData";
import { currencyFormat } from "../utils/amountToCurrencyString";
import { diffDatesByGranularityWithFilter } from "../utils/diffDatesByGranularity";

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

  const [shouldExchange, setShouldExchange] = useState(true);
  const { exchangedData, totalAmount, onlyExchangedCurrency, exchangeAvailable } = useExchangedData(
    data,
    shouldExchange,
  );

  const purchaseAmounts = data.length;
  const filteredAmount = diffDatesByGranularityWithFilter(filter);
  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: isFourColumn ? "span 3" : "span 4", sm: "span 1" }}
      gridRow="span 1"
      sx={sx}
      title={t("Purchase Revenue")}
    >
      <ExchangeSwitch
        checked={shouldExchange}
        disabled={!exchangeAvailable}
        onChange={() => setShouldExchange((prev) => !prev)}
      />
      {purchaseAmounts >= 2 ? (
        <>
          <SitesAmountsList data={exchangedData} isExchanged={shouldExchange} />
          {shouldExchange && onlyExchangedCurrency && (
            <SitesTotal amount={totalAmount} currency="SEK" />
          )}
        </>
      ) : (
        <Stack height="100%" px={2}>
          <Stack borderBottom="1px solid" borderColor="divider" height="100%">
            {purchaseAmounts === 1 ? (
              <Typography component="p" fontSize={28} fontWeight={700} variant="h5">
                {currencyFormat(
                  Number.parseFloat(exchangedData[0].amount),
                  exchangedData[0].currency,
                )}
              </Typography>
            ) : purchaseAmounts === 0 ? (
              <Stack height="100%">
                <Typography color="textSecondary" variant="caption">
                  {t("No revenue data for current period")}
                </Typography>
              </Stack>
            ) : null}
          </Stack>

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

export default PurchaseAmountWidget;
