import React, { useEffect, useState } from "react";
import html2canvas from "html2canvas";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  Button,
  Checkbox,
  Divider,
  FormControl,
  FormControlLabel,
  InputLabel,
  MenuItem,
  Popover,
  Select,
  Typography,
  IconButton,
  Dialog,
  DialogContent,
  DialogTitle,
} from "@mui/material";
import AddchartIcon from "@mui/icons-material/Addchart";
import FullscreenIcon from "@mui/icons-material/Fullscreen";
import FullscreenExitIcon from "@mui/icons-material/FullscreenExit";
import { useDispatch } from "react-redux";
import { visorsGetStaticsService } from "../../services/get-visors-statics";
import { Line } from "react-chartjs-2";
import CloseIcon from "@mui/icons-material/Close";
import FmdBadIcon from "@mui/icons-material/FmdBad";
import Accordion from "@mui/material/Accordion";
import AccordionSummary from "@mui/material/AccordionSummary";
import AccordionDetails from "@mui/material/AccordionDetails";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import DownloadIcon from "@mui/icons-material/Download";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import { formatJustDate, getPersianMonth } from "../../../../utils/formatTime";
import { RiFileExcel2Fill } from "react-icons/ri";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

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

export const VisorsStaticsMainPage = () => {
  // chart states
  const [barsState, setBarsState] = useState(false);
  const [bars, setBars] = useState(null);
  const [fullSizeChart, setFullSizeChart] = useState(null);

  // order state for charts
  const [chartOrder, setChartOrder] = useState([
    "hasCodeData",
    "quarantineQuantityData",
    "assignmentStateArchiveData",
    "acceptedAssignmentRealWeightData",
    "hasntCodeData",
    "differenceBarData",
    "wareHouseConfirmationData",
    "wareHouseAcceptedRealWeightData",
    "weightYearData",
  ]);

  // visibility states for each chart
  const [chartVisibility, setChartVisibility] = useState({
    hasCodeData: true,
    quarantineQuantityData: true,
    assignmentStateArchiveData: true,
    acceptedAssignmentRealWeightData: true,
    hasntCodeData: true,
    differenceBarData: true,
    wareHouseConfirmationData: true,
    wareHouseAcceptedRealWeightData: true,
    weightYearData: true,
  });

  // end charts
  const dispatch = useDispatch();
  const [anchorEl, setAnchorEl] = useState(null);

  const [threshold, setThreshold] = useState("threeMonths");
  const [fullSizeTitle, setFullSizeTitle] = useState("");

  const handleChange = (event) => {
    setThreshold(event.target.value);
  };

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleFullSizeOpen = (chartData) => {
    setFullSizeChart(chartData);
  };

  const handleFullSizeClose = () => {
    setFullSizeChart(null);
  };

  const handleVisibilityChange = (chartKey) => {
    setChartVisibility({
      ...chartVisibility,
      [chartKey]: !chartVisibility[chartKey],
    });
  };

  useEffect(() => {
    if (barsState) {
      dispatch(visorsGetStaticsService({ type: threshold })).then((r) => {
        setBars(r.payload.data);
      });
    } else {
      setBars(null);
    }
  }, [barsState, threshold]);

  const open = Boolean(anchorEl);
  const id = open ? "simple-popover" : undefined;

  const transformData = (data) => {
    return {
      labels:
        threshold !== "month"
          ? data.map((item) => getPersianMonth(item.date))
          : data.map((item) => formatJustDate(item.date)),
      datasets: [
        {
          label: "درصد",
          data: data.map((item) => item.percent),
          borderColor: "rgba(55, 41, 145, 0.6)",
          backgroundColor: "rgba(75, 192, 192, 0.2)",
        },
      ],
    };
  };

  const chartOptions = {
    scales: {
      y: {
        beginAtZero: true,
        min: 0,
      },
    },
  };

  const hasCodeData = bars ? transformData(bars.hasCode) : null;
  const quarantineQuantityData = bars
    ? transformData(bars.quarantineQuantity)
    : null;
  const differenceBarData = bars ? transformData(bars.differenceBar) : null;
  const assignmentStateArchiveData = bars
    ? transformData(bars.assignmentStateArchive)
    : null;
  const acceptedAssignmentRealWeightData = bars
    ? transformData(bars.acceptedAssignmentRealWeight)
    : null;
  const hasntCodeData = bars ? transformData(bars.hasntCode) : null;
  const wareHouseConfirmationData = bars
    ? transformData(bars.wareHouseConfirmation)
    : null;
  const wareHouseAcceptedRealWeightData = bars
    ? transformData(bars.wareHouseAcceptedRealWeight)
    : null;
  const weightYearData = bars ? transformData(bars.weightYear) : null;

  const chartsData = {
    hasCodeData: { title: "درصد بارهای دارای کد قرنطینه", data: hasCodeData },
    quarantineQuantityData: {
      title: "درصد تعداد بارهای احراز شده از قرنطینه",
      data: quarantineQuantityData,
    },
    assignmentStateArchiveData: {
      title: "درصد تعداد بارهای تکمیل شده کشتارگاه",
      data: assignmentStateArchiveData,
    },
    acceptedAssignmentRealWeightData: {
      title: "درصد وزن نهایی در کشتارگاه نسبت به وزن کل",
      data: acceptedAssignmentRealWeightData,
    },
    hasntCodeData: {
      title: "درصد بارهای فاقد کد قرنطینه",
      data: hasntCodeData,
    },
    differenceBarData: {
      title: "درصد بارهای اختلاف دار در قرنطینه و رصدیار",
      data: differenceBarData,
    },
    wareHouseConfirmationData: {
      title: "درصد تعداد بارهای ورودی به انبار",
      data: wareHouseConfirmationData,
    },
    wareHouseAcceptedRealWeightData: {
      title: "درصد وزن لاشه ها در انبار نسبت به وزن کل",
      data: wareHouseAcceptedRealWeightData,
    },
    weightYearData: {
      title: "درصد وزن لاشه در انبار نسبت به وزن نهایی در کشتارگاه",
      data: weightYearData,
    },
  };

  const handleDragStart = (event, index) => {
    event.dataTransfer.setData("draggedIndex", index);
  };

  const handleDrop = (event, dropIndex) => {
    const draggedIndex = event.dataTransfer.getData("draggedIndex");
    const reordered = Array.from(chartOrder);
    const [removed] = reordered.splice(draggedIndex, 1);
    reordered.splice(dropIndex, 0, removed);
    setChartOrder(reordered);
  };

  const handleDragOver = (event) => {
    event.preventDefault();
  };

  const downloadScreenshot = () => {
    const gridElement = document.getElementById("screenshot-container");
    html2canvas(gridElement).then((canvas) => {
      const link = document.createElement("a");
      link.href = canvas.toDataURL("image/png");
      link.download = "پایش آماری.png";
      link.click();
    });
  };

  const downloadSingleScreenshot = () => {
    const gridElement = document.getElementById("screenshot-single-container");
    html2canvas(gridElement).then((canvas) => {
      const link = document.createElement("a");
      link.href = canvas.toDataURL("image/png");
      link.download = "پایش آماری.png";
      link.click();
    });
  };

  return (
    <Grid container xs={12} alignItems="center" justifyContent="center" mt={2}>
      <Grid
        container
        xs={12}
        alignItems="center"
        justifyContent="center"
        p={2}
        style={{
          borderStyle: "solid",
          borderWidth: "2px",
          borderColor: "pink",
          borderRadius: "10px",
        }}
      >
        <Grid container xs={4}>
          <Popover
            id={id}
            open={open}
            anchorEl={anchorEl}
            onClose={handleClose}
            anchorOrigin={{
              vertical: "bottom",
              horizontal: "right",
            }}
            transformOrigin={{
              vertical: "top",
              horizontal: "left",
            }}
          >
            <Grid container width="300px" p={3}>
              <Grid
                container
                xs={12}
                justifyContent="space-between"
                alignItems="center"
              >
                <Typography variant="body1" color="primary">
                  انتخاب نمودار
                </Typography>
                <Button
                  color="error"
                  onClick={() => {
                    handleClose();
                  }}
                >
                  بازگشت
                </Button>
              </Grid>
              <Divider style={{ width: "100%" }} />
              <Grid container alignItems="center" gap={1} xs={12}>
                <FormControlLabel
                  control={
                    <Checkbox
                      size="small"
                      checked={barsState}
                      onChange={() => {
                        handleClose();
                        setBarsState(!barsState);
                      }}
                    />
                  }
                  label={"اطلاعات مدیریت بار"}
                />
                <Divider style={{ width: "100%" }} />
              </Grid>
            </Grid>
          </Popover>
        </Grid>
        <Grid
          container
          alignItems="center"
          gap={SPACING.SMALL}
          xs={12}
          justifyContent="start"
        >
          <Grid container gap={SPACING.TINY} alignItems="center">
            <Typography>پایش آماری</Typography>
          </Grid>

          <Button
            variant="contained"
            onClick={handleClick}
            aria-describedby={id}
            endIcon={<AddchartIcon />}
          >
            انتخاب نمودار
          </Button>

          <Grid container gap={SPACING.SMALL}>
            <FormControl fullWidth style={{ minWidth: "150px" }}>
              <InputLabel id="demo-simple-select-label">انتخاب بازه</InputLabel>
              <Select
                size="small"
                labelId="demo-simple-select-label"
                id="demo-simple-select"
                value={threshold}
                label="Age"
                onChange={handleChange}
              >
                <MenuItem value={"month"}>یک ماهه</MenuItem>
                <MenuItem value={"threeMonths"}>سه ماهه</MenuItem>
                <MenuItem value={"sixMonths"}>شش ماهه</MenuItem>
                <MenuItem value={"year"}>سالیانه</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          {getRoleFromUrl() === "AdminX" && (
            <Grid>
              <a
                href={`https://miran.storage.c2.liara.space/%D8%A2%D9%86%D8%A7%D9%84%DB%8C%D8%B2%20%D8%AC%D8%A7%D9%85%D8%B9%20%DA%A9%D8%B4%D8%AA%D8%A7%D8%B1%20%D8%A7%D8%B3%D8%AA%D8%A7%D9%86%20%D9%87%D9%85%D8%AF%D8%A7%D9%86%20%D8%B1%D8%B5%D8%AF%20%DB%8C%D8%A7%D8%B1.xlsx`}
                rel="noreferrer"
              >
                <Button color="success">
                  <RiFileExcel2Fill size={32} />
                </Button>
              </a>
            </Grid>
          )}
        </Grid>
        <Grid container xs={12}>
          {barsState && (
            <Grid
              container
              alignItems="center"
              onClick={() => {
                setBarsState(false);
                setBars(null);
              }}
              style={{ cursor: "pointer" }}
            >
              <IconButton color="error">
                <CloseIcon />
              </IconButton>{" "}
              <Typography color="error" variant="body2">
                اطلاعات مدیریت بار
              </Typography>
            </Grid>
          )}
        </Grid>
        <Divider
          style={{ width: "100%", marginTop: "20px", marginBottom: "20px" }}
        />

        <Grid
          container
          xs={12}
          mb={2}
          justifyContent="space-between"
          alignItems="center"
        >
          <Grid container alignItems="center" justifyContent="start">
            <FmdBadIcon color="primary" />
            <Typography variant="body2" color="primary">
              با کشیدن و رها کردن نمودارها میتوانید ترتیب نمایش آنها را تغییر
              دهید.{" "}
            </Typography>
          </Grid>
          <Grid>
            <IconButton
              onClick={downloadScreenshot}
              color="primary"
              disabled={!bars}
            >
              <DownloadIcon />
            </IconButton>
          </Grid>
        </Grid>

        {bars && (
          <Accordion>
            <AccordionSummary
              expandIcon={<ExpandMoreIcon />}
              aria-controls="panel1-content"
              id="panel1-header"
            >
              <Typography variant="body1" style={{ color: "gray" }}>
                فیلتر نمودارها
              </Typography>
            </AccordionSummary>
            <AccordionDetails>
              <Grid container xs={12}>
                {Object.keys(chartsData).map((chartKey) => (
                  <Grid
                    item
                    xs={12}
                    sm={6}
                    key={chartKey}
                    style={{ display: "flex", alignItems: "center" }}
                  >
                    <FormControlLabel
                      control={
                        <Checkbox
                          size="small"
                          checked={chartVisibility[chartKey]}
                          onChange={() => handleVisibilityChange(chartKey)}
                        />
                      }
                      label={chartsData[chartKey].title}
                    />
                  </Grid>
                ))}
              </Grid>
            </AccordionDetails>
          </Accordion>
        )}
      </Grid>

      <Grid container spacing={3} xs={12} mt={2} id="screenshot-container">
        {bars && (
          <>
            {chartOrder.map((chartKey, index) => {
              const chart = chartsData[chartKey];
              return (
                chartVisibility[chartKey] && (
                  <Grid
                    item
                    xs={12}
                    sm={6}
                    key={index}
                    style={{ position: "relative" }}
                    draggable
                    onDragStart={(event) => handleDragStart(event, index)}
                    onDrop={(event) => handleDrop(event, index)}
                    onDragOver={handleDragOver}
                    onDoubleClick={() => {
                      setFullSizeTitle(chart.title);
                      handleFullSizeOpen(chart.data);
                    }}
                  >
                    <Typography variant="h6" style={{ fontSize: "16px" }}>
                      {chart.title}
                    </Typography>
                    <IconButton
                      style={{
                        position: "absolute",
                        right: 10,
                        top: 10,
                        zIndex: 1,
                      }}
                      onClick={() => {
                        setFullSizeTitle(chart.title);
                        handleFullSizeOpen(chart.data);
                      }}
                    >
                      <FullscreenIcon />
                    </IconButton>
                    <Line data={chart.data} options={chartOptions} />
                  </Grid>
                )
              );
            })}
          </>
        )}
      </Grid>

      {fullSizeChart && (
        <Dialog
          open={Boolean(fullSizeChart)}
          onClose={handleFullSizeClose}
          maxWidth="md"
          fullWidth
        >
          <DialogTitle>
            <Grid
              container
              alignItems="center"
              justifyContent="space-between"
              xs={12}
            >
              <IconButton onClick={handleFullSizeClose}>
                <FullscreenExitIcon />
              </IconButton>
              <Grid>
                <IconButton onClick={downloadSingleScreenshot} disabled={!bars}>
                  <DownloadIcon />
                </IconButton>
              </Grid>
            </Grid>
          </DialogTitle>
          <DialogContent id="screenshot-single-container">
            <Grid container justifyContent="center" xs={12}>
              <Typography variant="h6" style={{ fontSize: "16px" }}>
                {fullSizeTitle}
              </Typography>
            </Grid>
            <Line data={fullSizeChart} />
          </DialogContent>
        </Dialog>
      )}
    </Grid>
  );
};
