import React, { ReactNode, useMemo } from 'react';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import { textToDate } from '../../../utils';
import type { ValueType, NameType, PayloadItem as BasePayloadItem } from '../../../utils';
import type { TooltipProps as BaseTooltipProps } from 'recharts';
import createClasses from './styles';

type PayloadItem = BasePayloadItem & {
  otherValue: number;
  count: number;
};

export interface CustomTooltipProps extends BaseTooltipProps<ValueType, NameType> {
  format?: string | undefined;
  showTitleValue?: boolean;
}

const CustomTooltip = (props: CustomTooltipProps) => {
  const { payload, active, label = '', format, labelFormatter, showTitleValue } = props;

  const showTooltip = useMemo(() => active && payload && payload.length > 0, [active, payload]);
  const classes = createClasses();

  const formattedLabel = useMemo(() => {
    if (labelFormatter && payload) {
      return labelFormatter(label, payload);
    }
    if (format === 'date') {
      return textToDate(label, {
        month: 'short',
        year: 'numeric'
      });
    }
    return label;
  }, [label, format, labelFormatter, payload]);

  const seperatedPayload = useMemo(
    () =>
      payload?.reduce((acc, value, index) => {
        const curIndex = Math.floor(index / 10);
        if (index >= 30 && acc[2] && acc[2][9] && payload[index].payload) {
          acc[2][9].name = '_!Other';

          acc[2][9].otherValue = acc[2][9].otherValue
            ? acc[2][9].otherValue
            : acc[2][9].value + Number(value.value);

          acc[2][9].count = acc[2][9].count
            ? acc[2][9].count
            : (acc[2][9].payload?.[`${acc[2][9].dataKey}-count`] || 0) +
              (payload[index].payload?.[`${payload[index].dataKey}-count`] || 0);
        } else {
          acc[curIndex] = acc[curIndex]?.concat(value);
        }
        return acc;
      }, Array(Math.floor(payload.length / 10) + 1).fill([])),
    [payload]
  );

  const payloadObj = payload?.[0]?.payload;
  let titleValue = 0;
  for (const key in payloadObj) {
    if (key.includes('count')) {
      titleValue += payloadObj[key];
    }
  }

  if (showTooltip) {
    return (
      <Grid container direction="column" className={classes.root}>
        <Typography component="h3" className={classes.title}>
          {showTitleValue ? `${formattedLabel} (${titleValue})` : formattedLabel}
        </Typography>
        <Grid container item>
          {seperatedPayload?.map((seperatedItem: PayloadItem[], index: number) => {
            return (
              <Grid
                container
                item
                xs
                direction="column"
                className={classes.itemContainer}
                key={`column-${index}`}
              >
                {seperatedItem?.map((item: PayloadItem, ind: number) => {
                  return (
                    <Typography className={classes.item} align="center" key={item?.name}>
                      <Typography component="span">
                        <Box
                          component="span"
                          className={classes.square}
                          style={{ backgroundColor: item?.color }}
                        />
                        <Typography component="span" className={classes.name}>
                          {item?.name?.split('_!')[1]}:
                        </Typography>
                      </Typography>
                      <Typography component="span">
                        <Typography component="span" className={classes.data}>
                          {!(index === 2 && ind === 9) ? item.value : item.otherValue}%
                        </Typography>

                        <Typography component="span" className={classes.data}>
                          {!(index === 2 && ind === 9)
                            ? item.payload[`${item.dataKey}-count`]
                            : item.count}
                        </Typography>
                      </Typography>
                    </Typography>
                  );
                })}
              </Grid>
            );
          })}
        </Grid>
      </Grid>
    );
  }

  return null;
};

CustomTooltip.defaultProps = {
  active: false,
  payload: [],
  format: 'date'
};

export default CustomTooltip;
