import * as React from "react";
import { Box, Paper, Typography } from "@mui/material";
import { ComponentProps } from "../report.props";
import ProgressCard from "./ProgressCard";
import { extractTopPayees } from "./TopPayees.adapter";

interface Props extends ComponentProps {
  compact?: boolean;
}

export default function TopPayees({
  reportData,
  state,
  stateSetters,
  header,
  compact = true,
  isFetching,
}: Props) {
  const { flow, selectedPeriodId, selectedGroupKey } = state;
  const { setSelectedGroupKey } = stateSetters;

  const { items, total } = React.useMemo(() => {
    return extractTopPayees(reportData, flow, selectedPeriodId, selectedGroupKey);
  }, [reportData, flow, selectedPeriodId, selectedGroupKey]);

  return (
    <Paper
      sx={{
        p: { xs: 2.5, sm: 4 },
        borderRadius: 4,
        width: "100%",
        boxShadow: "none",
        border: "1px solid",
        borderColor: "divider",
        bgcolor: "background.paper",
        opacity: isFetching ? 0.6 : 1,
        transition: "opacity 0.3s ease",
        pointerEvents: isFetching ? "none" : "auto",
      }}
    >
      <Typography variant="h6" fontWeight={700} gutterBottom>
        {header}
      </Typography>

      <Box
        sx={{
          display: "grid",
          gridTemplateColumns: {
            xs: "1fr",
            sm: "repeat(2, 1fr)",
            md: "repeat(4, 1fr)",
          },
          gap: 2,
        }}
      >
        {items.map((item) => {
          const isSelected = selectedGroupKey?.payee?.includes(item.name);
          return (
            <ProgressCard
              key={item.name}
              header={item.name}
              progressAmount={item.amount}
              totalAmount={total}
              compact={compact}
              colorTheme={flow === "outflows" ? "error" : "success"}
              selected={isSelected}
              isFetching={isFetching}
              onClick={() => {
                if (setSelectedGroupKey) {
                  let newKey = selectedGroupKey ? { ...selectedGroupKey } : {};

                  if (isSelected) {
                    delete newKey.payee;
                  } else {
                    newKey.payee = [item.name];
                  }

                  setSelectedGroupKey(Object.keys(newKey).length ? newKey : null);
                }
              }}
            />
          );
        })}
      </Box>
    </Paper>
  );
}
