import React, { useEffect, useState } from "react";
import { visorsGetNationalInfoService } from "../../../services/get-visor-national-info";
import { useDispatch } from "react-redux";
import { Line, Doughnut } from "react-chartjs-2"; // Add Bar to the imports
import { Grid } from "../../../../../components/grid/Grid";
import { Box, Typography } from "@mui/material";
import {
  Chart as ChartJS,
  ArcElement,
  Tooltip,
  Legend,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
} from "chart.js";
import { AdvancedChart } from "../../../../../components/advanced-chart/AdvancedChart";

ChartJS.register(
  ArcElement,
  Tooltip,
  Legend,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement
);

export const VisorStaticsNationalInfoBreeds = ({
  selectedProvince,
  selectedDate1,
  selectedDate2,
  withDate,
}) => {
  const dispatch = useDispatch();

  const [chartsData, setChartsData] = useState({});

  useEffect(() => {
    dispatch(
      visorsGetNationalInfoService({
        selectedProvince,
        selectedDate1,
        selectedDate2,
        withDate,
        type: "pedigree",
      })
    ).then((r) => {
      setChartsData(r.payload.data);
    });
  }, [dispatch, selectedProvince, selectedDate1, selectedDate2, withDate]);

  const getChartData = (name) => {
    let data;
    switch (name) {
      case "average-age":
        data = {
          labels: chartsData?.pedigreeNameAverageAge?.map(
            (item) => item?.PedigreeName
          ),
          chartList: chartsData?.pedigreeNameAverageAge?.map(
            (item) => item?.averageAge
          ),
        };
        break;
      case "hatching-sum":
        data = {
          labels: chartsData?.pedigreeNameHatchingSum?.map(
            (item) => item?.PedigreeName
          ),
          chartList: chartsData?.pedigreeNameHatchingSum?.map(
            (item) => item?.chickSum
          ),
        };
        break;
      case "hatching-count":
        data = {
          labels: chartsData?.pedigreeNameHatchingCount?.map(
            (item) => item?.PedigreeName
          ),
          chartList: chartsData?.pedigreeNameHatchingCount?.map(
            (item) => item?.chickCount
          ),
        };
        break;

      default:
        break;
    }

    if (name === "hatching-sum") {
      const backgroundColors = [
        "rgba(255, 99, 132, 0.7)",
        "rgba(54, 162, 235, 0.7)",
        "rgba(255, 206, 86, 0.7)",
        "rgba(75, 192, 192, 0.7)",
        "rgba(153, 102, 255, 0.7)",
        "rgba(255, 159, 64, 0.7)",
      ];

      return {
        labels: data?.labels,
        datasets: [
          {
            data: data?.chartList,
            backgroundColor: backgroundColors,
            borderColor: "#fff",
            borderWidth: 2,
            hoverOffset: 10,
          },
        ],
      };
    }

    return {
      labels: data?.labels,
      datasets: [
        {
          label: name === "hatching-count" ? "تعداد" : "سن",
          data: data?.chartList,
          borderColor: "#3A3A3A",
          backgroundColor: "rgba(16, 185, 129, 0.1)",
          borderWidth: 2,
          tension: 0.3,
          pointRadius: 0,
          pointHoverRadius: 6,
          pointBackgroundColor: "#3A3A3A",
          pointHoverBackgroundColor: "#3A3A3A",
          fill: true,
        },
      ],
    };
  };

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false,
        rtl: true,
        labels: {
          usePointStyle: true,
          padding: 20,
          font: {
            family: "iranyekan",
            size: 14,
          },
        },
      },
      tooltip: {
        mode: "index",
        intersect: false,
        backgroundColor: "#1E293B",
        titleFont: {
          family: "iranyekan",
          size: 14,
          weight: "bold",
        },
        bodyFont: {
          family: "iranyekan",
          size: 12,
        },
        padding: 12,
        cornerRadius: 8,
        displayColors: true,
        rtl: true,
      },
    },
    scales: {
      x: {
        grid: {
          display: false,
          drawBorder: false,
        },
        ticks: {
          color: "#64748B",
          font: {
            family: "iranyekan",
            size: 12,
          },
        },
      },
      y: {
        grid: {
          display: false,
          drawBorder: false,
        },
        ticks: {
          color: "#64748B",
          font: {
            family: "iranyekan",
            size: 11,
          },
          padding: 10,
        },
      },
    },
    interaction: {
      mode: "nearest",
      axis: "x",
      intersect: false,
    },
  };

  const doughnutOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: "right",
        rtl: true,
        labels: {
          usePointStyle: true,
          padding: 20,
          font: {
            family: "iranyekan",
            size: 14,
          },
        },
      },
      tooltip: {
        backgroundColor: "#1E293B",
        titleFont: {
          family: "iranyekan",
          size: 14,
          weight: "bold",
        },
        bodyFont: {
          family: "iranyekan",
          size: 12,
        },
        padding: 12,
        cornerRadius: 8,
        displayColors: true,
        rtl: true,
      },
    },
    cutout: "70%",
  };

  const getBreedByProvince = (originalData) => {
    if (originalData) {
      const allPedigrees = new Set();
      originalData.forEach((province) => {
        province.breeds.forEach((breed) => {
          allPedigrees.add(breed.pedigree);
        });
      });

      const pedigreeNames = Array.from(allPedigrees);

      const result = pedigreeNames.map((name) => {
        const data = originalData.map((province) => {
          const breed = province.breeds.find((b) => b.pedigree === name);
          return breed ? breed.hatchingSum : 0;
        });

        return {
          name: name,
          data: data,
        };
      });

      return result;
    } else {
      return null;
    }
  };

  const getEvacuationByPedigree = (originalData) => {
    if (originalData) {
      return [
        {
          name: "درصد تلفات نسبت به جوجه ریزی نژاد",
          data: originalData?.map((item) => item.pedigree),
        },
        {
          name: "درصد تلفات نسبت به کل جوجه ریزی",
          data: originalData?.map((item) => item.total),
        },
      ];
    } else {
      return null;
    }
  };

  return (
    <Grid
      xs={12}
      container
      justifyContent="center"
      alignItems="center"
      spacing={4}
      style={{ width: "100%" }}
    >
      <Grid item xs={12} sm={6} justifyContent="center" alignItems="center">
        <Typography mt={2} mb={2} variant="body2">
          میانگین سنی کشتار
        </Typography>
        <Box
          sx={{
            p: "24px",
            borderRadius: 2,
            height: "300px",
            background:
              "linear-gradient(180deg,rgba(255, 255, 255, 1) 0%, rgba(230, 250, 245, 1) 50%, rgba(230, 241, 253, 1) 100%)",
          }}
        >
          <Line data={getChartData("average-age")} options={chartOptions} />
        </Box>
      </Grid>
      <Grid item xs={12} sm={6} justifyContent="center" alignItems="center">
        <Typography mt={2} mb={2} variant="body2">
          حجم جوجه ریزی
        </Typography>
        <Box
          sx={{
            p: "24px",
            borderRadius: 2,
            height: "300px",
            background:
              "linear-gradient(180deg,rgba(255, 255, 255, 1) 0%, rgba(230, 250, 245, 1) 50%, rgba(230, 241, 253, 1) 100%)",
          }}
        >
          <Doughnut
            data={getChartData("hatching-sum")}
            options={doughnutOptions}
          />
        </Box>
      </Grid>
      {chartsData && (
        <Grid
          item
          xs={12}
          justifyContent="center"
          alignItems="center"
          height="700px"
        >
          <AdvancedChart
            title={"جوجه ریزی براساس نژاد"}
            type={"bar"}
            group
            seperator={chartsData?.provinceResult?.map(
              (province) => province.province
            )}
            info={getBreedByProvince(chartsData?.provinceResult)}
          />
        </Grid>
      )}
      <Grid item xs={6} justifyContent="center" alignItems="center">
        <Typography mt={2} mb={2} variant="body2">
          تعداد جوجه ریزی
        </Typography>
        <Box
          sx={{
            p: "24px",
            borderRadius: 2,
            height: "400px",
            background:
              "linear-gradient(180deg,rgba(255, 255, 255, 1) 0%, rgba(230, 250, 245, 1) 50%, rgba(230, 241, 253, 1) 100%)",
          }}
        >
          <Line data={getChartData("hatching-count")} options={chartOptions} />
        </Box>
      </Grid>
      <Grid item xs={6} justifyContent="center" alignItems="center">
        <Grid
          item
          xs={12}
          justifyContent="center"
          alignItems="center"
          height="700px"
        >
          <AdvancedChart
            title={"میزان تلفات به ازای هر نژاد"}
            type={"bar"}
            group
            seperator={chartsData?.pedigreeEvacuationHatchingPercent?.map(
              (pedigree) => pedigree.pedigreeName
            )}
            info={getEvacuationByPedigree(
              chartsData?.pedigreeEvacuationHatchingPercent
            )}
          />
        </Grid>
      </Grid>
    </Grid>
  );
};
