import { useCallback, useMemo } from "react";
import { Cell, Pie, PieChart, ResponsiveContainer } from "recharts";
import Dinero from "dinero.js";

export default function JobCostingPieComponent({ type = "sales", costCenterData }) {
  const Calculatedata = useCallback(
    (data) => {
      if (data && data.length > 0) {
        return data.reduce((acc, i) => {
          const value = type === "sales" ? Dinero(i.sales_dinero).getAmount() : Dinero(i.costs_dinero).getAmount();

          if (value > 0) {
            acc.push({
              name: i.cost_center,
              color: "#" + Math.floor(Math.random() * 16777215).toString(16),

              label: `${i.cost_center} - ${
                type === "sales" ? Dinero(i.sales_dinero).toFormat() : Dinero(i.costs_dinero).toFormat()
              }`,
              value: type === "sales" ? Dinero(i.sales_dinero).getAmount() : Dinero(i.costs_dinero).getAmount()
            });
          }
          return acc;
        }, []);
      } else {
        return [];
      }
    },
    [type]
  );

  const memoizedData = useMemo(() => Calculatedata(costCenterData), [costCenterData, Calculatedata]);

  return (
    <ResponsiveContainer width="100%" height={175} minHeight={100}>
      <PieChart>
        <Pie
          data={memoizedData}
          innerRadius={40}
          outerRadius={50}
          fill="#8884d8"
          paddingAngle={5}
          dataKey="value"
          label={(entry) => entry.label}
          labelLine
        >
          {memoizedData.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={entry.color} />
          ))}
        </Pie>
      </PieChart>
    </ResponsiveContainer>
  );
}
