import { useEffect, useState } from "react";
import Grid from "@mui/material/Grid";
import { useDispatch } from "react-redux";
import { AllProvinceDetailsForMap } from "../../services/all-province-details-for-map";
import NationalMapOverview from "./NationalMapOverview";
import NationalMapGuidline from "./NationalMapGuidline";

import NationalMapSumTotal from "./NationalMapSumTotal";

import NationalMapRadioBtn from "./NationalMapRadioBtn";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
const NationalMap = () => {
  const [tableData, setTableData] = useState([]);
  const [percentageType, setPercentageType] = useState("hatching"); // hatching or active
  const [provinceData, setProvinceData] = useState([]);
  const dispatch = useDispatch();

  const fetchTableData = () => {
    dispatch(AllProvinceDetailsForMap()).then((r) => {
      const data = r.payload?.data || [];
      setProvinceData(data);

      // const sum = data.reduce((total, item) => {
      //   return total + (item?.totalQuantity || 0);
      // }, 0);

      const d = data.map((item, i) => {
        return [
          i + 1,
          item?.provinceName || "",
          item?.totalQuantity?.toLocaleString() || "0",
          item?.totalKilledQuantity?.toLocaleString() || "0",
          item?.totalLeftOver?.toLocaleString() || "0",
          // sum.toLocaleString(),
          `% ${item?.totalHatchingLeftOverPercent.toLocaleString()} `,
          item?.totalActiveLeft.toLocaleString(),
          ` % ${item?.totalActiveLeftPercent.toLocaleString()}`,
        ];
      });

      setTableData(d);
    });
  };

  useEffect(() => {
    fetchTableData();
  }, []);

  const getColorByPercentage = (percent) => {
    if (percent < 25) return "#F18989";
    if (percent < 50) return "#FF944D";
    if (percent < 75) return "#F4C430";
    return "#61D8BA";
  };

  const provincePercentages = {};
  provinceData.forEach((item) => {
    if (item?.provinceName && item?.totalHatchingLeftOverPercent) {
      provincePercentages[item?.provinceName] =
        item?.totalHatchingLeftOverPercent;
    }
  });

  const getProvinceColor = (provinceName) => {
    const province = provinceData.find((p) => p?.provinceName === provinceName);
    if (!province) return "#B0B0B0";

    const percent =
      percentageType === "hatching"
        ? province?.totalHatchingLeftOverPercent
        : province?.totalActiveLeftPercent;

    return percent ? getColorByPercentage(percent) : "#B0B0B0";
  };

  const handlePercentageTypeChange = (type) => {
    setPercentageType(type);
  };

  return (
    <Grid xs={12} md={12} container spacing={2} justifyContent="center">
      <Grid
        item
        xs={12}
        md={4}
        gap={2}
        sx={{
          maxHeight: { xs: "auto", md: "668px" },
          overflowY: "scroll",
        }}
      >
        <ResponsiveTable
          title="اطلاعات کشتار زنده کشتارگاه"
          columns={[
            "ردیف",
            " استان",
            " جوجه ریزی",
            "کشتار شده",
            "مانده در سالن",
            " مانده در سالن",
            "آماده کشتار",
            " آماده کشتار",
          ]}
          data={tableData}
          sx={{
            "& .MuiTableCell-root": {
              fontSize: "0.75rem",
              padding: "8px",
            },
            "& .MuiTableHead-root": {
              "& .MuiTableCell-root": {
                fontWeight: 600,
              },
            },
          }}
        />
      </Grid>

      <Grid
        xs={12}
        md={7}
        gap={2}
        sx={{
          display: "flex",
          flexDirection: "column",
          marginLeft: { xs: "0px", md: "33px" },
        }}
      >
        <NationalMapSumTotal />
        <NationalMapRadioBtn
          onPercentageTypeChange={handlePercentageTypeChange}
          selectedPercentageType={percentageType}
        />
        <NationalMapOverview getProvinceColor={getProvinceColor} />

        <NationalMapGuidline />
      </Grid>
    </Grid>
  );
};

export default NationalMap;
