"use client";
import {
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  Cell,
  Legend,
} from "recharts";
import { useEffect, useState } from "react";

type PieChartData = {
  name: string;
  total: number;
};

type CombinedPieChartProps = {
  categoriesData: PieChartData[];
  collectionsData: PieChartData[];
};

export function CombinedPieChart({
  categoriesData,
  collectionsData,
}: CombinedPieChartProps) {
  const [isSmallScreen, setIsSmallScreen] = useState(false);

  useEffect(() => {
    const handleResize = () => {
      setIsSmallScreen(window.innerWidth <= 1024); 
    };
    handleResize();

    window.addEventListener("resize", handleResize);

    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const CATEGORIES_COLORS = [
    "#7a78c1",
    "#9c98e1",
    "#766fbc",
    "#a8a4e3",
    "#6562a8",
    "#5a4da8",
    "#4d42a3",
    "#6d5aa2",
  ];
  //  const CATEGORIES_COLORS = [
  //    "#01b8eb",
  //    "#03a8d1",
  //    "#05a8e3",
  //    "#2bb7eb",
  //    "#1e9edb",
  //    "#4cc9e7",
  //    "#00a5d8",
  //  ];
  const COLLECTIONS_COLORS = [
    "#82ca9d",
    "#78b8a3",
    "#6dbb9a",
    "#6ab79a",
    "#7ab89b",
    "#75d2a8",
    "#6fd4a2",
    "#6ecf9d",
  ];

  const totalCategories = categoriesData.reduce(
    (sum, item) => sum + item.total,
    0
  );
  const totalCollections = collectionsData.reduce(
    (sum, item) => sum + item.total,
    0
  );

  const renderLabel = ({ percent }: { percent: number }) => {
    return `${(percent * 100).toFixed(0)}%`;
  };

  const renderLegend = (props: any) => {
    const { payload } = props;
    return (
      <ul className="list-none p-0 text-sm max-md:text-xs max-sm:hidden">
        {payload.map((entry: any, index: number) => (
          <li key={`item-${index}`} className="mb-1">
            <span style={{ color: entry.color }}>{entry.value}</span>:{" "}
            {(
              (entry.payload.total /
                (entry.payload.type === "Category"
                  ? totalCategories
                  : totalCollections)) *
              100
            ).toFixed(0)}
            %
          </li>
        ))}
      </ul>
    );
  };

  return (
    <ResponsiveContainer
      width="100%"
      height={250}
      className="max-sm:h-[160px] max-md:h-[180px] lg:h-[250px] p-2"
    >
      <PieChart>
        <Pie
          data={categoriesData}
          dataKey="total"
          nameKey="name"
          cx={isSmallScreen ? "50%" : "28%"}
          cy="50%"
          outerRadius={isSmallScreen? 62 : 76}
          fill="#8884d8"
          //fill="#01b8eb"
          label={isSmallScreen ? undefined : renderLabel}
        >
          {categoriesData.map((entry, index) => (
            <Cell
              key={`cell-${index}`}
              fill={CATEGORIES_COLORS[index % CATEGORIES_COLORS.length]}
            />
          ))}
        </Pie>

        {/* Collections Pie */}
        <Pie
          data={collectionsData}
          dataKey="total"
          nameKey="name"
          cx={isSmallScreen ? "50%" : "74%"}
          cy="50%"
          innerRadius={66}
          outerRadius={94}
          fill="#82ca9d"
          label={renderLabel}
        >
          {collectionsData.map((entry, index) => (
            <Cell
              key={`cell-${index}`}
              fill={COLLECTIONS_COLORS[index % COLLECTIONS_COLORS.length]}
            />
          ))}
        </Pie>

        <Tooltip />
        <Legend
          content={renderLegend}
          layout="vertical"
          align="right"
          verticalAlign="top"
          wrapperStyle={{
            paddingLeft: "8px",
            paddingRight: "6px",
          }}
          className="max-md:!static max-md:mt-2"
        />
      </PieChart>
    </ResponsiveContainer>
  );
}