import { Skeleton, Typography } from "antd";
import Dinero from "dinero.js";
import React, { useMemo } from "react";
import { Cell, Pie, PieChart, ResponsiveContainer } from "recharts";
import ErrorResultAtom from "../error-result/error-result.atom";
import partTypeConverterAtom from "../part-type-converter/part-type-converter.atom";
export default function JobPartsGraphAtom({
  job,
  loading,
  price = "act_price",
}) {
  const data = useMemo(() => {
    if (!job) return [];

    const sums = job.joblines
      .filter((j) => !j.ignore)
      .reduce((acc, val) => {
        if (!acc[val.part_type]) {
          acc[val.part_type] = Dinero();
        }

        acc[val.part_type] = acc[val.part_type].add(
          Dinero({ amount: Math.round((val[price] || 0) * 100) })
          // .multiply(
          //   val.part_qty || 1
          // )
        );

        return acc;
      }, {});

    return Object.keys(sums).map((key) => {
      return {
        name: key,
        value: sums[key].getAmount() / 100,
        label: sums[key].toFormat(),
        color: getColor(key),
      };
    });
  }, [job, price]);

  if (loading) return <Skeleton active />;
  if (!job)
    return (
      <ErrorResultAtom
        title="Error displaying parts graphs."
        errorMessage="It looks like this job doesn't exist."
      />
    );

  return (
    <div
      style={{
        display: "flex",
        flex: 1,
        flexDirection: "column",
        alignItems: "center",
      }}
    >
      <ResponsiveContainer>
        <PieChart>
          <Pie
            data={data}
            innerRadius={40}
            outerRadius={80}
            fill="#8884d8"
            // paddingAngle={5}
            dataKey="value"
            label={(entry) =>
              `${partTypeConverterAtom(entry.name)} (${entry.label})`
            }
            labelLine
          >
            {data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={entry.color} />
            ))}
          </Pie>
        </PieChart>
      </ResponsiveContainer>
      <Typography.Title level={4}>
        {price === "act_price" ? "Actual Price" : "Database Price"}
      </Typography.Title>
    </div>
  );
}

const getColor = (key) => {
  switch (key) {
    case "PAA":
      return "slategray";
    case "PAL":
      return "dodgeblue";
    case "PAN":
      return "seagreen";
    default:
      return "slategray";
  }
};
