import { Box } from "@mui/material";
import React, { useEffect, useState } from "react";
import { Treemap, Tooltip, ResponsiveContainer } from "recharts";

interface ProfitBySymbols {
  value?: number;
  sum: string
  symbol: string
}

interface ProfitBySymbolsWidgetProps {
  data: ProfitBySymbols[];
}

interface renderItemProps {
  x: number;
  y: number;
  width: number;
  height: number;
  value: string;
  index: number;
}

const COLORS = ['#006943', '#00603D', '#00482E'];

const ProfitBySymbolsWidget = ({ data }: ProfitBySymbolsWidgetProps) => {
  const [myData, setMyData] = useState<ProfitBySymbols[]>([]);

  const renderItem = ({ x, y, width, height, index, value }: renderItemProps) => {
    const getColor = (index: number) => {
      if (index < data.length / 3) {
        return COLORS[0];
      } else if (index < (data.length / 3) * 2) {
        return COLORS[1];
      } else {
        return COLORS[2];
      }
    };

    return (
      <g>
        <rect
          x={x}
          y={y}
          width={width}
          height={height}
          rx={9}
          ry={9}
          style={{
            fill: getColor(index),
            stroke: "#000",
            strokeWidth: 2,
            padding: 3
          }}
        />
        <text
          x={x + width / 2}
          y={
            height < 100 ? y + height / 2 - 2
              : height < 90
                ? y + height / 2
                : y + height / 2 + 7
          }
          textAnchor="middle"
          fill="#fff"
          display={width < 50 || height < 35 ? "none" : ""}
          fontWeight={300}
          fontSize={width < 60 || height < 60 ? 10
            : width < 100 || height < 100 ? 14
              : 18}
        >
          {myData[index].symbol}
        </text>
        <text
          x={x + width / 2}
          y={
            height < 100 ? y + height / 2 + 13
              : height < 90
                ? y + height / 2 + 7
                : y + height / 2 + 27}
          textAnchor="middle"
          display={width < 50 || height < 35 ? "none" : ""}
          fill="#fff"
          fontWeight={300}
          fontSize={width < 70 || height < 70 ? 10
            : width < 100 || height < 100 ? 13
              : 16}
        >
          ${parseFloat(`${myData[index].sum}`).toFixed(2)}
        </text>
      </g>
    );
  };

  useEffect(() => {
    if (data.length === 0) return

    let absData = data.map(item => Math.abs(+item.sum));
    let minAbs = Math.min(...absData);
    let maxAbs = Math.max(...absData);

    const percentageData = absData.map(item => {
      const percentage = ((item - minAbs) * 99 / (maxAbs - minAbs)) + 1;
      return parseFloat(percentage.toFixed(2));
    });

    const updatedData = data.map((item, index) => {
      return {
        ...item,
        value: percentageData[index],
      };
    }).sort((a, b) => b.value - a.value);
    setMyData(updatedData)
  }, [data])

  if (myData.length === 0) return <></>
  return (
    <Box height="100%" className="parent-box">
      <ResponsiveContainer width="100%" height="100%">
        <Treemap
          data={myData}
          aspectRatio={1}
          dataKey="value"
          //@ts-ignore
          content={({ x, y, width, height, value, index }: any) => {
            return renderItem({ x, y, width, height, value, index });
          }}
        >
          <Tooltip content={<CustomTooltip />} />
        </Treemap>
      </ResponsiveContainer>
    </Box>
  );
};
https://recharts.org/en-US/examples/CustomContentTreemap
https://recharts.org/en-US/api/Treemap
 стыки между renderItem  надо полностью черным залить, а где нету стыка, то есть снаружи никаких бордеров быть не должно, только где соприкасаются блоки внутри, где нужно разделать