import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Line, Pie } from "react-chartjs-2";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { SPACING } from "../../../../data/spacing";
import { AppContext } from "../../../../contexts/AppContext";
import { DatePicker } from "@mui/x-date-pickers";
import { TextField, Typography } from "@mui/material";
import moment from "moment";

import { AdvancedChart } from "../../../../components/advanced-chart/AdvancedChart";
import { useDispatch } from "react-redux";
import { dashboardGetSlaughterManagementKillHouse } from "../../services/dashboard-slaughter-performance";

ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels);
export const DashboardSlaughterPerformance = () => {
  const dispatch = useDispatch();
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [data, setData] = useState({});

  useEffect(() => {
    dispatch(
      dashboardGetSlaughterManagementKillHouse({
        date1: selectedDate1,
        date2: selectedDate2,
      })
    ).then((r) => {
      if (r.payload?.data) {
        setData(r.payload.data);
      }
    });
  }, [dispatch, selectedDate1, selectedDate2]);

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      datalabels: {
        color: "#fff",
        font: {
          size: 10,
          family: "iranyekan",
        },
        formatter: (value, context) => {
          const percentage = context.dataset.data[context.dataIndex];
          return percentage > 10 ? `${percentage}%` : "";
        },
        clamp: true,
        anchor: "center",
        align: "center",
        offset: 0,
        clip: true,
      },
      legend: {
        labels: {
          color: "#333",
          font: {
            size: 12,
          },
        },
      },
    },
  };

  const lineOptions = {
    scales: {
      y: {
        beginAtZero: true,
      },
    },
    plugins: {
      rtl: true,
    },
  };
  const firstChart = [
    data?.allManagementKillHouseData?.stewardAllocations || 0,
    data?.allManagementKillHouseData?.freeBars || 0,
    data?.allManagementKillHouseData?.inWarehouse || 0,
  ];

  const firstChartData = {
    labels: [
      "وزن توزیع شده داخل استان",
      "وزن توزیع شده خارج استان",
      "وزن وارد شده به انبار",
    ],
    datasets: [
      {
        label: "",
        data: firstChart?.map((v) =>
          ((v / firstChart.reduce((a, b) => a + b, 0)) * 100).toFixed(0)
        ),

        backgroundColor: ["#2D5FFF", "#00CC99", "#dada95"],
      },
    ],
  };

  const secondChart = [
    data?.allManagementKillHouseData?.inWarehouse || 0,
    data?.totalWeightHasntWarehouse || 0,
    data?.poultryHatchingTotalKilledWeight || 0,
  ];

  const secondChartData = {
    labels: [
      "وزن وارد شده به انبار",
      "وزن کل کشتار شده",
      "وزن وارد نشده به انبار",
    ],
    datasets: [
      {
        label: "",
        data: secondChart.map((v) =>
          ((v / secondChart.reduce((a, b) => a + b, 0)) * 100).toFixed(1)
        ),

        backgroundColor: ["#2D5FFF", "#00CC99", "#dada95"],
      },
    ],
  };

  const getChartOptions = () => {
    return [
      {
        name: "درصد توزیع به خارج استان",
        data: data?.managementKillHouseData?.map((item) => {
          const killHouse = parseFloat(item?.killHouseFreeBarQuantity || 0);
          const all = parseFloat(item?.allQuantity || 0);
          return all ? parseFloat(((killHouse / all) * 100).toFixed(0)) : 0;
        }),
      },
      {
        name: "درصد توزیع به داخل استان",
        data: data?.managementKillHouseData?.map((item) => {
          const inProvince = parseFloat(item?.inProvinceQuantity || 0);
          const all = parseFloat(item?.allQuantity || 0);
          return all ? parseFloat(((inProvince / all) * 100).toFixed(0)) : 0;
        }),
      },
      {
        name: "درصد مانده در انبار",
        data: data?.managementKillHouseData?.map((item) => {
          const product = parseFloat(item?.product || 0);
          const all = parseFloat(item?.allQuantity || 0);
          return all ? parseFloat(((product / all) * 100).toFixed(0)) : 0;
        }),
      },
      {
        name: "درصد توزیع",
        // data: data?.managementKillHouseData?.map(() => 100),
        data: data?.managementKillHouseData?.map(
          (item) =>
            item?.inProvinceQuantity + item?.killHouseFreeBarQuantity || 0
        ),
      },
    ];
  };

  const getChartStewardOptions = () => {
    return [
      {
        name: "وزن کل تخصیصات",
        data: data?.killHousesData?.map(
          (item) => item?.wightOfSteward + item?.wightOfGuild || 0
        ),
      },
      {
        name: "وزن تخصیصات به مباشرین",
        data: data?.killHousesData?.map((item) => item?.wightOfSteward || 0),
      },
      {
        name: "وزن تخصیصات به صنوف",
        data: data?.killHousesData?.map((item) => item?.wightOfGuild || 0),
      },
    ];
  };

  const lineData = {
    labels: data?.killHousesData?.map((item) => item?.name),
    datasets: [
      {
        label: "وزن توزیع خارج استان",
        data: data?.killHousesData?.map((item) => item?.outProvinceWeight || 0),
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgba(255, 99, 132, 1)",
        borderWidth: 1,
      },
      {
        label: "وزن توزیع داخل استان",
        data: data?.killHousesData?.map((item) => item?.inProvinceWight || 0),
        backgroundColor: "rgba(54, 162, 235, 0.2)",
        borderColor: "rgba(54, 162, 235, 1)",
        borderWidth: 1,
      },
      {
        label: "کل وزن مانده به انبار",
        data: data?.killHousesData?.map((item) => item?.totalWeight),
        backgroundColor: "rgba(75, 192, 192, 0.2)",
        borderColor: "rgba(75, 192, 192, 1)",
        borderWidth: 1,
      },
    ],
  };

  return (
    <Grid container xs={12} md={12}>
      <Grid
        container
        gap={1}
        sx={{
          padding: "8px",
          alignItems: "center",
        }}
      >
        <Grid>
          <DatePicker
            label="از تاریخ"
            renderInput={(params) => (
              <TextField {...params} style={{ width: "160px" }} size="small" />
            )}
            value={selectedDate1}
            onChange={(newValue) => {
              setSelectedDate1(moment(newValue).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            renderInput={(params) => (
              <TextField {...params} style={{ width: "160px" }} size="small" />
            )}
            value={selectedDate2}
            onChange={(newValue) => {
              setSelectedDate2(moment(newValue).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
      </Grid>
      <Grid
        container
        gap={1}
        justifyContent="center"
        alignItems="center"
        sx={{ width: "100%", mt: SPACING.SMALL }}
      >
        <Grid
          item
          xs={12}
          md={5.9}
          sx={{
            // height: "400px",
            display: "flex",
            border: "1px solid #CCCCCD",
            backgroundColor: "#F9F9FA",
            borderRadius: "20px",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
            padding: "20px",
          }}
        >
          <Typography align="right" sx={{ color: "#2D5FFF" }} variant="body1">
            عملکرد کشتارگاه ها در بخش توزیع
          </Typography>

          <Grid sx={{ height: "400px", width: "400px" }}>
            <Pie data={firstChartData} options={options} />
          </Grid>

          <Grid
            container
            sx={{
              display: "flex",
              flexWrap: "wrap",
              gap: "16px",
              padding: "10px",
            }}
          >
            {[
              {
                label: "وزن وارد شده به انبار",
                value: data?.allManagementKillHouseData?.inWarehouse,
              },
              {
                label: "وزن توزیع شده خارج استان",
                value: data?.allManagementKillHouseData?.freeBars,
              },
              {
                label: "وزن توزیع شده داخل استان",
                value: data?.allManagementKillHouseData?.stewardAllocations,
              },
              {
                label: "مانده انبار",
                value: data?.allManagementKillHouseData?.products,
              },
            ].map((item, index) => (
              <Grid
                key={index}
                item
                sx={{
                  display: "flex",
                  justifyContent: "center",
                  flex: "1 1 calc(50% - 8px)",
                  backgroundColor: "#E0E7FF",
                  color: "#717171",
                  borderRadius: "8px",
                  p: 2,
                  boxSizing: "border-box",
                }}
              >
                <Typography sx={{ display: "flex" }}>
                  {item.label} : {item.value?.toLocaleString()}
                </Typography>
              </Grid>
            ))}
          </Grid>
        </Grid>
        <Grid
          item
          xs={12}
          md={5.9}
          sx={{
            // height: "400px",
            display: "flex",
            border: "1px solid #CCCCCD",
            backgroundColor: "#F9F9FA",
            borderRadius: "20px",
            flexDirection: "column",
            justifyContent: "center",
            alignItems: "center",
            padding: "20px",
          }}
        >
          <Typography align="left" sx={{ color: "#2D5FFF" }} variant="body1">
            عملکرد کشتارگاه ها در بخش ورود و خروج بارها به انبار
          </Typography>
          <Grid sx={{ height: "400px", width: "400px" }}>
            <Pie data={secondChartData} options={options} />
          </Grid>
          <Grid
            container
            sx={{
              display: "flex",
              flexWrap: "wrap",
              gap: "24px",
              padding: "10px",
            }}
          >
            {[
              {
                label: "وزن وارد شده به انبار",
                value: data?.allManagementKillHouseData?.inWarehouse,
              },
              {
                label: "وزن توزیع شده خارج استان",
                value: data?.allManagementKillHouseData?.freeBars,
              },
              {
                label: "وزن توزیع شده داخل استان",
                value: data?.allManagementKillHouseData?.stewardAllocations,
              },
              {
                label: "مانده انبار",
                value: data?.allManagementKillHouseData?.products,
              },
            ].map((item, index) => (
              <Grid
                key={index}
                item
                sx={{
                  display: "flex",
                  justifyContent: "center",
                  flex: "1 1 calc(50% - 12px)",
                  backgroundColor: "#E0E7FF",
                  color: "#717171",
                  borderRadius: "8px",
                  p: 2,
                  boxSizing: "border-box",
                }}
              >
                <Typography sx={{ display: "flex" }}>
                  {item.label} : {item.value?.toLocaleString()}
                </Typography>
              </Grid>
            ))}
          </Grid>
        </Grid>
      </Grid>

      {data?.killHousesData?.length > 0 && (
        <Grid
          md={12}
          xs={12}
          container
          spacing={SPACING.SMALL}
          sx={{
            justifyContent: "center",
            border: "1px solid #CCCCCD",
            backgroundColor: "#F9F9FA",
            borderRadius: "20px",
            marginTop: "9px",
            padding: "5px",
          }}
        >
          <Grid
            sx={{
              width: "100%",
              padding: "24px",
            }}
          >
            <Typography
              align="left"
              sx={{
                color: "#2D5FFF",
                padding: "10px",
              }}
              variant="body1"
            >
              گزارش درصد خرید کشتارگاه های استان (بر اساس حجم)
            </Typography>

            <Grid
              sx={{
                display: "flex",
                gap: "22px",
              }}
            >
              {data?.killHousesData?.map((item, idx) => (
                <Grid
                  md={4}
                  xs={12}
                  key={idx}
                  spacing={4}
                  style={{
                    backgroundColor: idx % 2 === 0 ? "#2D5FFF1C" : "#E6FAF5",
                    border: "1px solid #ccc",
                    borderRadius: "8px",
                    margin: "10px",
                    maxHeight: "250px",
                    padding: "0",
                  }}
                >
                  <Grid
                    style={{
                      borderRadius: "8px",
                      backgroundColor: idx % 2 === 0 ? "#6C8FFF" : "#00CC99",
                    }}
                  >
                    <Typography
                      variant="caption"
                      style={{
                        color: "#fff",
                      }}
                    >
                      {item?.name}
                    </Typography>
                  </Grid>
                  <Grid style={{ marginTop: "5px" }}>
                    <Typography variant="body2" style={{ color: "#535353" }}>
                      درصد خرید داخل استان:
                    </Typography>
                    <Typography
                      style={{
                        color: "#353535",
                        fontSize: "24px",
                        fontWeight: "400",
                      }}
                    >
                      {(() => {
                        return `${
                          Math.floor(
                            ((item?.inProvinceQuantity || 0) /
                              (item?.totalQuantity || 0)) *
                              100
                          ) || 0
                        }% `;
                      })()}
                    </Typography>
                    <Typography variant="body2" style={{ color: "#535353" }}>
                      درصد خرید خارج استان:
                    </Typography>
                    <Typography
                      style={{
                        color: "#353535",
                        fontSize: "24px",
                        fontWeight: "400",
                      }}
                    >
                      {(() => {
                        return `${
                          Math.floor(
                            ((item?.outProvinceQuantity || 0) /
                              (item?.totalQuantity || 0)) *
                              100
                          ) || 0
                        }% `;
                      })()}
                    </Typography>
                  </Grid>
                </Grid>
              ))}
            </Grid>
          </Grid>
        </Grid>
      )}

      {data?.managementKillHouseData?.length > 0 && (
        <Grid
          mt={2}
          xs={12}
          md={12}
          justifyContent="center"
          alignItems="center"
          height="400px"
          sx={{
            border: "1px solid #CCCCCD",
            backgroundColor: "#F9F9FA",
            borderRadius: "20px",
          }}
        >
          <Typography
            align="left"
            sx={{ color: "#2D5FFF", padding: "20px" }}
            variant="body1"
          >
            گزارش عملکرد انبار و توزیع کشتارگاه های استان (بر اساس درصد)
          </Typography>

          <AdvancedChart
            type={"bar"}
            group
            seperator={data?.managementKillHouseData?.map((item) => item?.name)}
            info={getChartOptions()}
          />
        </Grid>
      )}
      {data?.killHousesData?.length > 0 && (
        <Grid
          container
          gap={1}
          justifyContent="center"
          alignItems="center"
          sx={{ width: "100%", marginTop: "9px" }}
        >
          <Grid
            item
            mt={2}
            md={5.9}
            xs={12}
            sx={{
              justifyContent: "center",
              border: "1px solid #CCCCCD",
              backgroundColor: "#F9F9FA",
              borderRadius: "20px",
              padding: "5px",
            }}
          >
            <Grid sx={{ width: "100%", padding: "10px" }}>
              <Typography
                align="left"
                sx={{
                  color: "#2D5FFF",
                }}
                variant="body1"
              >
                گزارش درصد خرید کشتارگاه های استان (بر اساس وزن)
              </Typography>

              <Grid
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  gap: "2px",
                }}
              >
                <Grid
                  sx={{
                    display: "flex",
                    justifyContent: "space-around",
                    color: "#717171",
                  }}
                >
                  <Typography>نام کشتارگاه</Typography>
                  <Typography>درصد خرید از استان</Typography>
                  <Typography>درصد خرید از خارج استان</Typography>
                </Grid>

                {data.killHousesData.map((item, idx) => (
                  <Grid
                    item
                    md={12}
                    xs={12}
                    key={idx}
                    spacing={6}
                    style={{
                      backgroundColor: idx % 2 === 0 ? "#E0E7FF" : "#FFFFFF",
                      border: "1px solid #ccc",
                      borderRadius: "8px",
                      height: "48px",
                      display: "flex",
                      justifyContent: "space-around",
                      alignItems: "center",
                    }}
                  >
                    <Typography>{item?.name}</Typography>

                    <Typography>
                      {(() => {
                        const total = parseFloat(item?.totalWeight) || 0;
                        const inProvince =
                          parseFloat(item?.inProvinceWight) || 0;
                        return total > 0
                          ? `${((inProvince / total) * 100).toFixed(0)}%`
                          : "0%";
                      })()}
                    </Typography>

                    <Typography>
                      {(() => {
                        const total = parseFloat(item?.totalWeight) || 0;
                        const outProvince =
                          parseFloat(item?.outProvinceWeight) || 0;
                        return total > 0
                          ? `${((outProvince / total) * 100).toFixed(0)}%`
                          : "0%";
                      })()}
                    </Typography>
                  </Grid>
                ))}
              </Grid>
            </Grid>
          </Grid>
          <Grid
            item
            mt={2}
            md={5.9}
            xs={12}
            sx={{
              justifyContent: "center",
              border: "1px solid #CCCCCD",
              backgroundColor: "#F9F9FA",
              borderRadius: "20px",
              padding: "5px",
            }}
          >
            {data?.killHousesData?.length > 0 && (
              <Grid sx={{ width: "100%", padding: "10px" }}>
                <Typography
                  align="left"
                  sx={{
                    color: "#2D5FFF",
                  }}
                  variant="body1"
                >
                  گزارش کلی عملکرد توزیع به مباشرین و صنوف استان
                </Typography>

                <Grid
                  sx={{
                    display: "flex",
                    flexDirection: "column",
                    gap: "2px",
                  }}
                >
                  <Grid
                    sx={{
                      display: "flex",
                      justifyContent: "space-around",
                      color: "#717171",
                    }}
                  >
                    <Typography>نام کشتارگاه</Typography>
                    <Typography>تعداد تخصیصات به مباشرین</Typography>
                    <Typography>تعداد تخصیصات به صنوف</Typography>
                  </Grid>

                  {data.killHousesData.map((item, idx) => (
                    <Grid
                      md={12}
                      xs={12}
                      key={idx}
                      spacing={6}
                      style={{
                        backgroundColor: idx % 2 === 0 ? "#E0E7FF" : "#FFFFFF",
                        border: "1px solid #ccc",
                        borderRadius: "8px",
                        height: "48px",
                        display: "flex",
                        justifyContent: "space-around",
                        alignItems: "center",
                      }}
                    >
                      <Typography>{item?.name}</Typography>

                      <Typography>{item?.lenOfSteward}</Typography>

                      <Typography>{item?.lenOfGuild}</Typography>
                    </Grid>
                  ))}
                </Grid>
              </Grid>
            )}
          </Grid>
        </Grid>
      )}

      {data?.managementKillHouseData?.length > 0 && (
        <Grid container md={12} xs={12}>
          <Grid
            item
            mt={2}
            xs={12}
            md={12}
            justifyContent="center"
            alignItems="center"
            sx={{
              border: "1px solid #CCCCCD",
              backgroundColor: "#F9F9FA",
              borderRadius: "20px",
            }}
          >
            <Typography
              align="left"
              sx={{
                color: "#2D5FFF",
                padding: "10px",
              }}
              variant="body1"
            >
              گزارش کلی عملکرد توزیع به مباشرین و صنوف استان (بر اساس وزن)
            </Typography>
            <Grid container justifyContent="center" sx={{ maxHeight: "400px" }}>
              <Line data={lineData} options={lineOptions} />
            </Grid>
          </Grid>
        </Grid>
      )}

      <Grid
        container
        gap={1}
        justifyContent="center"
        alignItems="center"
        sx={{ width: "100%" }}
      >
        <Grid
          item
          mt={2}
          md={5.9}
          xs={12}
          sx={{
            justifyContent: "center",
            border: "1px solid #CCCCCD",
            backgroundColor: "#F9F9FA",
            borderRadius: "20px",
            padding: "5px",
          }}
        >
          <Grid sx={{ width: "100%", padding: "10px" }}>
            <Typography
              align="left"
              sx={{
                color: "#2D5FFF",
                padding: "10px",
              }}
              variant="body1"
            >
              گزارش درصد خرید کشتارگاه های استان (بر اساس وزن)
            </Typography>
            <Grid sx={{ height: "400px" }}>
              <AdvancedChart
                type={"bar"}
                group
                seperator={data?.killHousesData?.map((item) => item?.name)}
                info={getChartStewardOptions()}
              />
            </Grid>
          </Grid>
        </Grid>

        <Grid
          item
          mt={2}
          md={5.9}
          xs={12}
          sx={{
            justifyContent: "center",
            border: "1px solid #CCCCCD",
            backgroundColor: "#F9F9FA",
            borderRadius: "20px",
            padding: "5px",
            height: "472px",
          }}
        >
          <Grid sx={{ width: "100%", padding: "10px" }}>
            <Typography
              align="left"
              sx={{
                color: "#2D5FFF",
                padding: "10px",
              }}
              variant="body1"
            >
              گزارش کلی عملکرد توزیع به مباشرین و صنوف استان (درصد)
            </Typography>

            <Grid
              sx={{
                display: "flex",
                flexDirection: "column",
                gap: "2px",
              }}
            >
              <Grid
                sx={{
                  display: "flex",
                  justifyContent: "space-around",
                  color: "#717171",
                }}
              >
                <Typography>نام کشتارگاه</Typography>
                <Typography>تعداد تخصیصات به مباشرین</Typography>
                <Typography>تعداد تخصیصات به صنوف</Typography>
              </Grid>

              {data?.killHousesData?.map((item, idx) => (
                <Grid
                  md={12}
                  xs={12}
                  key={idx}
                  spacing={6}
                  style={{
                    backgroundColor: idx % 2 === 0 ? "#E0E7FF" : "#FFFFFF",
                    border: "1px solid #ccc",
                    borderRadius: "8px",
                    height: "48px",
                    display: "flex",
                    justifyContent: "space-around",
                    alignItems: "center",
                  }}
                >
                  <Typography>{item?.name}</Typography>
                  <Typography>
                    {(() => {
                      const stewardWeight =
                        parseFloat(item?.wightOfSteward) || 0;
                      const guildWeight = parseFloat(item?.wightOfGuild) || 0;
                      const total = stewardWeight + guildWeight;

                      const steward = parseFloat(item?.lenOfSteward) || 0;

                      return total > 0
                        ? `${((steward / total) * 100).toFixed(0)}%`
                        : "0%";
                    })()}
                  </Typography>

                  <Typography>
                    {(() => {
                      const total =
                        parseFloat(item?.wightOfSteward + item?.wightOfGuild) ||
                        0;
                      const guild = parseFloat(item?.lenOfGuild) || 0;
                      return total > 0
                        ? `${((guild / total) * 100).toFixed(0)}%`
                        : "0%";
                    })()}
                  </Typography>
                </Grid>
              ))}
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};
