import { useMemo } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { AdvancedChart } from "../../../../components/advanced-chart/AdvancedChart";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ProvinceTradePanelMarketRequest } from "../province-trade-panel-market-request/ProvinceTradePanelMarketRequest";

export const TradePanelChart = ({ chartsData, updateTable }) => {
  const chartOptions = useMemo(() => {
    if (!chartsData || !Array.isArray(chartsData) || !chartsData[0]) {
      return [];
    }

    const firstItem = chartsData[0];
    if (!firstItem?.category || !Array.isArray(firstItem.category)) {
      return [
        {
          name: "تعداد کل",
          data: chartsData.map((item) => item?.totalQuantity || 0),
        },
      ];
    }

    const formatCategoryName = (category) =>
      `بین ${category?.minValue || 0} تا ${category?.maxValue || 0}`;

    return [
      {
        name: "تعداد کل",
        data: chartsData.map((item) => item?.totalQuantity || 0),
      },
      ...firstItem.category.map((cat, index) => ({
        name: formatCategoryName(cat),
        data: chartsData.map((item) => {
          if (!item?.category || !Array.isArray(item.category)) return 0;
          return item.category[index]?.quantity || 0;
        }),
      })),
    ];
  }, [chartsData]);

  const chartSeparator =
    chartsData && Array.isArray(chartsData)
      ? chartsData.map((item) => item?.city || "")
      : [];

  const isKillHouse = getRoleFromUrl() === "KillHouse";

  return (
    <Grid container spacing={2} xs={12}>
      <Grid
        xs={12}
        md={isKillHouse ? 5 : 12}
        justifyContent="center"
        alignItems="center"
        height="400px"
      >
        <AdvancedChart
          title="درخواست های کشتار بر اساس وزن"
          type="bar"
          group
          seperator={chartSeparator}
          info={chartOptions}
        />
      </Grid>
      {isKillHouse && (
        <Grid xs={12} md={7}>
          <ProvinceTradePanelMarketRequest updateTable={updateTable} />
        </Grid>
      )}
    </Grid>
  );
};
