import { useCallback, useMemo } from "react";
import { connect } from "react-redux";
import { Cell, Pie, PieChart, ResponsiveContainer } from "recharts";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useTranslation } from "react-i18next";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

export function PartsStatusPie({ bodyshop, joblines_status }) {
  const { t } = useTranslation();
  const pieColor = useCallback(
    (status) => {
      if (status === bodyshop.md_order_statuses.default_ordered) return "lightgreen";
      if (status === bodyshop.md_order_statuses.default_bo) return "crimson";

      if (status === bodyshop.md_order_statuses.default_canceled) return "dodgerblue";

      if (status === bodyshop.md_order_statuses.default_returned) return "powderblue";
      if (status === bodyshop.md_order_statuses.default_received) return "seagreen";

      return "slategray";
    },
    [
      bodyshop.md_order_statuses.default_ordered,
      bodyshop.md_order_statuses.default_bo,
      bodyshop.md_order_statuses.default_canceled,
      bodyshop.md_order_statuses.default_returned,
      bodyshop.md_order_statuses.default_received
    ]
  );

  const Calculatedata = useCallback(
    (data) => {
      if (data && data.length > 0) {
        const statusMapping = {};
        data.map((i) => {
          if (!statusMapping[i.status])
            statusMapping[i.status] = {
              name: i.status || t("joblines.labels.nostatus"),
              value: 0,
              color: pieColor(i.status)
            };
          statusMapping[i.status].value = statusMapping[i.status].value + i.count;
          return null;
        });
        return Object.keys(statusMapping).map((key) => {
          return statusMapping[key];
        });
      } else {
        return [];
      }
    },
    [pieColor, t]
  );

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

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

export default connect(mapStateToProps, null)(PartsStatusPie);
