import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import moment from "moment";
import { Button, Chip, TextField, Typography } from "@mui/material";
import { RiSearchLine } from "react-icons/ri";
import { dashboardGetEquivalentInfoService } from "../../services/dahsboard-get-equivalent-info";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import ReactECharts from "echarts-for-react";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import InfoIcon from "@mui/icons-material/Info";
import { formatJustDate } from "../../../../utils/formatTime";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";

export const DashboardEquivalentTab = () => {
  const [
    openNotif,
    ,
    selectedDate1,
    setSelectedDate1,
    selectedDate2,
    setSelectedDate2,
  ] = useContext(AppContext);
  const [textValue, setTextValue] = useState("");
  const [data, setData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [has500Error, setHas500Error] = useState(false);

  const dispatch = useDispatch();
  const colorScheme = {
    rasad: "#5b5b9d",
    quarantine: "#bf5757",
  };

  function subtractOneDay(dateString) {
    if (!dateString) {
      return "";
    }
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        return "";
      }
      date.setDate(date.getDate() - 1);

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");

      return `${year}-${month}-${day}`;
    } catch (error) {
      console.error("Error subtracting one day:", error);
      return "";
    }
  }

  const staticLineChartData = {
    data:
      data && Array.isArray(data)
        ? data.map((series) => series?.name || "").filter((name) => name)
        : [],
    series: [
      {
        name: "رصدیار",
        type: "line",
        data:
          data && Array.isArray(data)
            ? data.map((itm) => {
                const value = parseInt(itm?.info?.totalLiveBarsQuantity);
                return isNaN(value) ? 0 : value;
              })
            : [],
        itemStyle: { color: "#5470c6" },
      },
      {
        name: "قرنطینه",
        type: "line",
        data:
          data && Array.isArray(data)
            ? data.map((itm) => {
                const value = parseInt(
                  itm?.info?.killHouseRsiInfo?.info?.totalWareHouse
                );
                return isNaN(value) ? 0 : value;
              })
            : [],
        itemStyle: { color: "#fac858" },
      },
    ],
  };

  const staticDistributionLineChartData = {
    data:
      data && Array.isArray(data)
        ? data.map((series) => series?.name || "").filter((name) => name)
        : [],
    series: [
      {
        name: "رصدیار",
        type: "line",
        data:
          data && Array.isArray(data)
            ? data.map((itm) => {
                const value = parseInt(
                  itm?.info?.totalKillHouseWarehouseCacassesEnteredWeight
                );
                return isNaN(value) ? 0 : value;
              })
            : [],
        itemStyle: { color: "#5470c6" },
      },
      {
        name: "قرنطینه",
        type: "line",
        data:
          data && Array.isArray(data)
            ? data.map((itm) => {
                const value = parseInt(
                  itm?.info?.killHouseRsiInfo?.info?.totalBarsWight
                );
                return isNaN(value) ? 0 : value;
              })
            : [],
        itemStyle: { color: "#fac858" },
      },
    ],
  };

  const getCarcassDate = () => {
    if (!selectedDate1) {
      return "";
    }
    if (selectedDate1 === selectedDate2) {
      return formatJustDate(subtractOneDay(selectedDate1)) || "";
    } else {
      const date1 = formatJustDate(subtractOneDay(selectedDate1)) || "";
      const date2 = selectedDate2
        ? formatJustDate(subtractOneDay(selectedDate2)) || ""
        : "";
      return `${date1} تا ${date2}`;
    }
  };

  const barChartOption = {
    title: {
      text: `گزارش کل توزیع لاشه رصدیار و قرنطینه `,
      textStyle: {
        fontFamily: "iranyekan",
        fontSize: 16,
      },
      right: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      textStyle: {
        fontFamily: "iranyekan",
        fontSize: 12,
      },
      backgroundColor: "rgba(255, 255, 255, 0.95)",
      borderColor: "#ddd",
      borderWidth: 1,
      formatter: function (params) {
        if (!params || !Array.isArray(params) || params.length === 0) {
          return "";
        }
        let result = `<div style="font-weight: bold; margin-bottom: 5px;">${
          params[0]?.name || ""
        }</div>`;
        params.forEach((param) => {
          if (param) {
            const value =
              param.value !== undefined && param.value !== null
                ? param.value.toLocaleString()
                : "0";
            result += `
                    <div style="display: flex; align-items: center; margin: 2px 0;">
                        <span style="display: inline-block; width: 12px; height: 12px; background: ${
                          param.color || "#000"
                        }; margin-left: 5px; border-radius: 2px;"></span>
                        ${param.seriesName || ""}: ${value}
                    </div>
                `;
          }
        });
        return result;
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      top: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data:
        data && Array.isArray(data)
          ? data.map((itm) => itm?.name || "").filter((name) => name)
          : [],
      axisLabel: {
        fontFamily: "iranyekan",
      },
      name: "کشتارگاه",
    },
    yAxis: {
      type: "value",
      axisLabel: {
        fontFamily: "iranyekan",
        formatter: "{value}",
      },
      name: "وزن",
    },
    series: [
      {
        name: "توزیع داخل استان (R)",
        type: "bar",
        data:
          data && Array.isArray(data)
            ? data.map((itm) => itm?.info?.totalKillHouseAllocationsWeight || 0)
            : [],
        itemStyle: { color: "#fac858" },
        emphasis: { focus: "series" },
      },
      {
        name: "توزیع خارج استان (R)",
        type: "bar",
        data:
          data && Array.isArray(data)
            ? data.map((itm) => itm?.info?.totalKillHouseFreeSaleBarWeight || 0)
            : [],
        itemStyle: { color: "#c4a051" },
        emphasis: { focus: "series" },
      },
      {
        name: "توزیع داخل استان (G)",
        type: "bar",
        data:
          data && Array.isArray(data)
            ? data.map((itm) => {
                const value = parseInt(
                  itm?.info?.killHouseRsiInfo?.info?.totalInputBarsWight
                );
                return isNaN(value) ? 0 : value;
              })
            : [],
        itemStyle: { color: "#5470c6" },
        emphasis: { focus: "series" },
      },
      {
        name: "توزیع خارج استان (G)",
        type: "bar",
        data:
          data && Array.isArray(data)
            ? data.map((itm) => {
                const value = parseInt(
                  itm?.info?.killHouseRsiInfo?.info?.totalOutputBarsWight
                );
                return isNaN(value) ? 0 : value;
              })
            : [],
        itemStyle: { color: "#364982" },
        emphasis: { focus: "series" },
      },
    ],
  };

  const lineChartOption = {
    title: {
      text: `گزارش حجم کشتار زنده قرنطینه و رصدیار ${getCarcassDate()}`,
      textStyle: {
        fontFamily: "iranyekan",
        fontSize: 16,
      },
      right: "center",
    },
    tooltip: {
      trigger: "axis",
      textStyle: {
        fontFamily: "iranyekan",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      top: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: staticLineChartData.data,
      axisLabel: {
        fontFamily: "iranyekan",
      },
      name: "کشتارگاه",
    },
    yAxis: {
      type: "value",
      axisLabel: {
        fontFamily: "iranyekan",
        formatter: "{value}",
      },
      name: "حجم",
    },
    series:
      staticLineChartData?.series && Array.isArray(staticLineChartData.series)
        ? staticLineChartData.series.map((series) => ({
            ...series,
            smooth: true,
            lineStyle: {
              width: 3,
            },
            symbolSize: 8,
          }))
        : [],
  };

  const distributionLineChartOption = {
    title: {
      text: `گزارش کل توزیع لاشه رصدیار و قرنطینه`,
      textStyle: {
        fontFamily: "iranyekan",
        fontSize: 16,
      },
      right: "center",
    },
    tooltip: {
      trigger: "axis",
      textStyle: {
        fontFamily: "iranyekan",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      top: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: staticDistributionLineChartData.data,
      axisLabel: {
        fontFamily: "iranyekan",
      },
      name: "کشتارگاه",
    },
    yAxis: {
      type: "value",
      axisLabel: {
        fontFamily: "iranyekan",
        formatter: "{value}",
      },
      name: "وزن",
    },
    series:
      staticDistributionLineChartData?.series &&
      Array.isArray(staticDistributionLineChartData.series)
        ? staticDistributionLineChartData.series.map((series) => ({
            ...series,
            smooth: true,
            lineStyle: {
              width: 3,
            },
            symbolSize: 8,
          }))
        : [],
  };

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  useEffect(() => {
    if (!data || !Array.isArray(data)) {
      setTableData([]);
      return;
    }

    const safeParseInt = (value) => {
      const parsed = parseInt(value);
      return isNaN(parsed) ? 0 : parsed;
    };

    const safeToLocaleString = (value) => {
      const parsed = safeParseInt(value);
      return parsed.toLocaleString();
    };

    const d = data.map((item, i) => {
      const totalBarsWight = safeParseInt(
        item?.info?.killHouseRsiInfo?.info?.totalBarsWight
      );
      const totalWareHouse = safeParseInt(
        item?.info?.killHouseRsiInfo?.info?.totalWareHouse
      );
      const totalInputBarsWight = safeParseInt(
        item?.info?.killHouseRsiInfo?.info?.totalInputBarsWight
      );
      const totalOutputBarsWight = safeParseInt(
        item?.info?.killHouseRsiInfo?.info?.totalOutputBarsWight
      );
      const totalLiveBarsQuantity = safeParseInt(
        item?.info?.totalLiveBarsQuantity
      );
      const totalEnteredWarehouseBarsQuantity = safeParseInt(
        item?.info?.totalEnteredWarehouseBarsQuantity
      );
      const totalKillHouseWarehouseCacassesEnteredWeight = safeParseInt(
        item?.info?.totalKillHouseWarehouseCacassesEnteredWeight
      );
      const totalOutputWeight = safeParseInt(item?.info?.totalOutputWeight);

      return [
        i + 1,
        item?.name || "",
        safeToLocaleString(totalWareHouse),
        safeToLocaleString(Math.floor(totalWareHouse * 2.6)),
        safeToLocaleString(totalBarsWight),
        totalBarsWight && totalWareHouse
          ? "%" +
            Math.floor((totalBarsWight * 100) / (totalWareHouse * 2.6 * 0.75))
          : 0,
        safeToLocaleString(totalInputBarsWight),
        totalInputBarsWight && totalBarsWight
          ? "%" + ((totalInputBarsWight * 100) / totalBarsWight).toFixed(1)
          : 0,
        safeToLocaleString(totalOutputBarsWight),
        totalOutputBarsWight && totalBarsWight
          ? "%" + ((totalOutputBarsWight * 100) / totalBarsWight).toFixed(1)
          : 0,
        safeToLocaleString(totalLiveBarsQuantity),
        safeToLocaleString(
          item?.info?.totalKillHouseRequestGovernmentalQuantity
        ),
        safeToLocaleString(item?.info?.totalKillHouseRequestFreeQuantity),
        safeToLocaleString(item?.info?.totalKillHouseFreeBarLiveTotalQuantity),
        safeToLocaleString(totalEnteredWarehouseBarsQuantity),
        totalEnteredWarehouseBarsQuantity && totalLiveBarsQuantity
          ? "%" +
            Math.floor(
              (totalEnteredWarehouseBarsQuantity * 100) / totalLiveBarsQuantity
            )
          : 0,
        safeToLocaleString(item?.info?.totalEnteredWarehouseBarsWeight),
        safeToLocaleString(totalKillHouseWarehouseCacassesEnteredWeight),
        safeToLocaleString(
          item?.info?.totalKillHouseWarehouseGovermentalCacassesEnteredWeight
        ),
        safeToLocaleString(
          item?.info?.totalKillHouseWarehouseFreeCacassesEnteredWeight
        ),
        safeToLocaleString(totalOutputWeight),
        totalOutputWeight && totalKillHouseWarehouseCacassesEnteredWeight
          ? "%" +
            Math.floor(
              (totalOutputWeight * 100) /
                totalKillHouseWarehouseCacassesEnteredWeight
            )
          : 0,
        safeToLocaleString(item?.info?.totalKillHouseAllocationsWeight),
        safeToLocaleString(item?.info?.totalKillHouseFreeSaleBarWeight),
        safeToLocaleString(item?.info?.totalOtherOutputWeight),
        safeToLocaleString(item?.info?.totalRemainWeight),
        safeToLocaleString(item?.info?.totalRemainFreeWeight),
        safeToLocaleString(item?.info?.totalRemainGovernmentalWeight),
        safeToLocaleString(item?.info?.lastTotalRemainWeight),
        safeToLocaleString(item?.info?.lastTotalRemainGovernmentalWeight),
        safeToLocaleString(item?.info?.lastTotalRemainFreeWeight),
      ];
    });

    setTableData(d);
  }, [data]);

  useEffect(() => {
    // Prevent request if there was a 500 error
    if (has500Error) {
      return;
    }

    dispatch(LOADING_START());
    dispatch(
      dashboardGetEquivalentInfoService({
        date1: selectedDate1,
        date2: selectedDate2,
        filter: "search",
        value: textValue || null,
        role: getRoleFromUrl(),
      })
    )
      .then((r) => {
        if (r?.error) {
          const errorMessage = r.error?.message || "";
          const is500Error =
            errorMessage.includes("500") ||
            r.error?.status === 500 ||
            r.error?.statusCode === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          }
          setData([]);
        } else if (r?.payload?.data) {
          // Reset error state on successful response
          setHas500Error(false);
          setData(Array.isArray(r.payload.data) ? r.payload.data : []);
        } else {
          setData([]);
        }
      })
      .catch((error) => {
        console.error("Error fetching equivalent info:", error);
        const errorMessage = error?.message || "";
        const is500Error =
          errorMessage.includes("500") ||
          error?.status === 500 ||
          error?.statusCode === 500;

        if (is500Error) {
          setHas500Error(true);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        }
        setData([]);
      })
      .finally(() => {
        dispatch(LOADING_END());
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch, selectedDate1, selectedDate2, openNotif]);

  // Reset error state when dates change
  useEffect(() => {
    setHas500Error(false);
  }, [selectedDate1, selectedDate2]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    // Reset error state on manual submit (user retry)
    setHas500Error(false);
    dispatch(LOADING_START());
    dispatch(
      dashboardGetEquivalentInfoService({
        date1: selectedDate1,
        date2: selectedDate2,
        filter: "search",
        value: textValue || null,
        role: getRoleFromUrl(),
      })
    )
      .then((r) => {
        if (r?.error) {
          const errorMessage = r.error?.message || "";
          const is500Error =
            errorMessage.includes("500") ||
            r.error?.status === 500 ||
            r.error?.statusCode === 500;

          if (is500Error) {
            setHas500Error(true);
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
              severity: "error",
            });
          }
          setData([]);
        } else if (r?.payload?.data) {
          // Reset error state on successful response
          setHas500Error(false);
          setData(Array.isArray(r.payload.data) ? r.payload.data : []);
        } else {
          setData([]);
        }
      })
      .catch((error) => {
        console.error("Error fetching equivalent info:", error);
        const errorMessage = error?.message || "";
        const is500Error =
          errorMessage.includes("500") ||
          error?.status === 500 ||
          error?.statusCode === 500;

        if (is500Error) {
          setHas500Error(true);
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی در دریافت اطلاعات پیش آمده است!",
            severity: "error",
          });
        }
        setData([]);
      })
      .finally(() => {
        dispatch(LOADING_END());
      });
  };

  return (
    <Grid
      container
      justifyContent="center"
      alignItems="center"
      xs={12}
      direction="column"
      mt={2}
    >
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField size="small" style={{ width: "160px" }} {...params} />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField size="small" style={{ width: "160px" }} {...params} />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>

      <Grid
        container
        xs={12}
        justifyContent="center"
        alignItems="center"
        gap={1}
      >
        <Grid container xs={12} spacing={1} mt={2}>
          <Grid item>
            <Chip
              label="رصدیار (R)"
              size="small"
              sx={{
                backgroundColor: colorScheme.rasad,
                color: "white",
                fontSize: "0.75rem",
              }}
            />
          </Grid>
          <Grid item>
            <Chip
              label="قرنطینه (G)"
              size="small"
              sx={{
                backgroundColor: colorScheme.quarantine,
                color: "white",
                fontSize: "0.75rem",
              }}
            />
          </Grid>
        </Grid>
        <Grid
          container
          alignItems="center"
          justifyContent="start"
          xs={12}
          gap={1}
          sx={{ color: "red" }}
        >
          <InfoIcon size={24} />
          <Typography variant="caption">
            ملاک حجم، قطعه و ملاک وزن، کیلوگرم میباشد.
          </Typography>
        </Grid>
        <Grid
          container
          alignItems="start"
          justifyContent="start"
          xs={12}
          gap={1}
          sx={{ color: "red", display: "flex" }}
        >
          <InfoIcon size={24} />
          <Typography
            variant="caption"
            textAlign="left"
            sx={{ maxWidth: { xs: "80%", sm: "90%" } }}
          >
            اطلاعات کشتار زنده مربوط به یک روز قبل ({getCarcassDate()}) می باشد.
          </Typography>
        </Grid>

        <ResponsiveTable
          title={`مقایسه اطلاعات کشتار رصدیار با قرنطینه`}
          paginated
          columns={[
            "ردیف",
            "کشتارگاه",
            "حجم بارهای زنده (G)",
            "وزن تقریبی بار زنده (G)",
            "کل وزن توزیع لاشه (G)",
            "درصد توزیع کل لاشه (G)",
            "وزن توزیع لاشه داخل استان (G)",
            "درصد توزیع داخل استان (G)",
            "وزن توزیع لاشه خارج استان (G)",
            "درصد توزیع خارج استان (G)",
            "کل حجم بارهای زنده (R)",
            // "حجم کشتار (R)",
            "حجم بار زنده دولتی (R)",
            "حجم بار زنده آزاد (R)",
            "حجم بار خرید خارج استان (R)",
            "حجم بارهای ورودی به انبار (R)",
            "درصد ورودی به انبار (R)",
            "وزن بارهای ورودی به انبار (R)",
            "وزن لاشه (R)",
            "وزن لاشه دولتی (R)",
            "وزن لاشه آزاد (R)",
            "کل وزن توزیع لاشه (R)",
            "درصد توزیع لاشه (R)",
            "وزن توزیع لاشه داخل استان (R)",
            "وزن توزیع لاشه خارج استان (R)",
            "وزن سایر توزیع (R)",
            "مانده لاشه (R)",
            "مانده لاشه آزاد (R)",
            "مانده لاشه دولتی (R)",
            "انبار گذشته (R)",
            "انبار دولتی گذشته (R)",
            "انبار آزاد گذشته (R)",
          ]}
          data={tableData}
          CustomColumnsColor={[
            { key: "(G)", color: colorScheme.quarantine, text: "white" },
            { key: "(R)", color: colorScheme.rasad, text: "white" },
            { key: "", color: "gray", text: "white" },
          ]}
          hasSum
          hasSumColumn="کشتارگاه"
        />
      </Grid>

      <Grid item xs={12} style={{ height: "400px" }}>
        <ReactECharts
          option={barChartOption}
          style={{ height: "100%", width: "100%" }}
          opts={{ renderer: "svg" }}
        />
        <Grid
          xs={12}
          container
          justifyContent="center"
          gap={2}
          alignItems="center"
        >
          {barChartOption?.series?.map((itm, i) => (
            <Grid container gap={1} key={i} alignItems="center">
              <Grid>
                <Typography variant="caption">{itm?.name}</Typography>
              </Grid>
              <Grid
                sx={{
                  width: "20px",
                  height: "20px",
                  background: itm?.itemStyle?.color,
                }}
              ></Grid>
            </Grid>
          ))}
        </Grid>
      </Grid>

      <Grid container xs={12} spacing={3} mt={6}>
        <Grid
          container
          gap={1}
          xs={12}
          md={6}
          style={{ height: "400px" }}
          justifyContent="center"
          alignItems="center"
        >
          <ReactECharts
            option={lineChartOption}
            style={{ height: "100%", width: "100%" }}
            opts={{ renderer: "svg" }}
          />
          {staticLineChartData?.series?.map((itm, i) => (
            <Grid container gap={1} key={i} alignItems="center">
              <Grid>
                <Typography variant="caption">{itm?.name}</Typography>
              </Grid>
              <Grid
                sx={{
                  width: "20px",
                  height: "20px",
                  background: itm?.itemStyle?.color,
                }}
              ></Grid>
            </Grid>
          ))}
        </Grid>

        <Grid
          container
          gap={1}
          xs={12}
          md={6}
          style={{ height: "400px" }}
          justifyContent="center"
          alignItems="center"
        >
          <ReactECharts
            option={distributionLineChartOption}
            style={{ height: "100%", width: "100%" }}
            opts={{ renderer: "svg" }}
          />
          {staticDistributionLineChartData?.series?.map((itm, i) => (
            <Grid container gap={1} key={i} alignItems="center">
              <Grid>
                <Typography variant="caption">{itm?.name}</Typography>
              </Grid>
              <Grid
                sx={{
                  width: "20px",
                  height: "20px",
                  background: itm?.itemStyle?.color,
                }}
              ></Grid>
            </Grid>
          ))}
        </Grid>
      </Grid>
      <Grid mt={4}>{"‌‌‌  ‌"}</Grid>
    </Grid>
  );
};
