import React, { useState } from "react";

import { useTheme } from "@mui/material/styles";
import { SeriesId } from "@mui/x-charts/internals";

import BarChart from "../../../components/charts/BarChart";
import WidgetCard from "../../../components/WidgetCard";
import { useDashboardFilter } from "../../../contexts/DashboardFilterContext";
import { useI18n } from "../../../contexts/I18nContext";
import { ContribComponent } from "../../../types";
import { granularityLabel } from "../../../types/dashboard";
import { SubscriptionEventCountItem } from "../types/stats";

const SubscriptionEventCountWidget: ContribComponent<SubscriptionEventCountItem[]> = ({
  data,
  sx,
}) => {
  const { filter } = useDashboardFilter();
  const { t } = useI18n();
  const theme = useTheme();

  const [highlighted, setHighlighted] = useState<SeriesId>("none");

  const maxCount = Math.max(
    ...data.map(({ created, started, cancelled, ended }) =>
      Math.max(created, started, cancelled, ended),
    ),
  );

  return (
    <WidgetCard
      gridColumn={{ md: "span 6", sm: "span 1" }}
      gridRow="span 2"
      sx={sx}
      title={t(`${granularityLabel(filter.granularity)} Subscription Events`)}
    >
      <BarChart
        dataKeyX="timestamp"
        dataset={data.map(({ timestamp, ...stats }) => ({
          timestamp: new Date(timestamp),
          ...stats,
        }))}
        granularity={filter.granularity}
        highlightedSerie={highlighted}
        legendProps={{
          onItemClick: (_, context) =>
            setHighlighted(highlighted !== context.seriesId ? context.seriesId : "none"),
        }}
        series={[
          {
            id: "created",
            label: "Created",
            stack: "pending",
            data: data.map(({ created }) => created),
            color: theme.palette.info.light,
            highlightScope: { fade: "global", highlight: "series" },
          },
          {
            id: "started",
            label: "Started",
            stack: "running",
            data: data.map(({ started }) => started),
            color: theme.palette.success.main,
            highlightScope: { fade: "global", highlight: "series" },
          },
          {
            id: "cancelled",
            label: "Cancelled",
            stack: "pending",
            data: data.map(({ cancelled }) => (cancelled === 0 ? 0 : -cancelled)),
            color: theme.palette.warning.main,
            highlightScope: { fade: "global", highlight: "series" },
          },
          {
            id: "ended",
            label: "Ended",
            stack: "running",
            data: data.map(({ ended }) => (ended === 0 ? 0 : -ended)),
            color: theme.palette.error.light,
            highlightScope: { fade: "global", highlight: "series" },
          },
        ]}
        yAxisOptions={{
          min: maxCount < 10 ? -(maxCount + 1) : undefined,
          max: maxCount < 10 ? maxCount + 1 : undefined,
          tickNumber: undefined,
          tickMinStep: 1,
        }}
      />
    </WidgetCard>
  );
};

export default SubscriptionEventCountWidget;
