import { useLayoutEffect, useState } from "react";
import {
  Box,
  Button,
  IconButton,
  Paper,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import dayjs from "dayjs";
import { DatePicker } from "@mui/x-date-pickers";
import { LineChart } from "@mui/x-charts";
import moment from "moment";
import { useQuizStore } from "@root/quizes/store";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useAnalytics } from "@utils/hooks/useAnalytics";

import HeaderFull from "@ui_kit/Header/HeaderFull";
import SectionWrapper from "@ui_kit/SectionWrapper";

import { General } from "./General";
import { AnswersStatistics } from "./Answers";
import { Devices } from "./Devices";

import CalendarIcon from "@icons/CalendarIcon";
import { redirect } from "react-router-dom";

import type { Dayjs } from "dayjs";

export default function Analytics() {
  const quiz = useCurrentQuiz();
  const { editQuizId } = useQuizStore();

  const [isOpen, setOpen] = useState(false);
  const [isOpenEnd, setOpenEnd] = useState(false);
  const [from, setFrom] = useState<Dayjs>(dayjs(0));
  const [to, setTo] = useState<Dayjs>(dayjs(Date.now()));

  console.log(11, to);
  const { devices, general, questions } = useAnalytics({
    quizId: editQuizId?.toString() || "",
    to: to.unix(),
    from: from.unix(),
  });

  const resetTime = () => {
    setTo(dayjs(Date.now()));
    setFrom(dayjs(0));
  };
  useLayoutEffect(() => {
    if (editQuizId === undefined) redirect("/list");
  }, [editQuizId]);
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const isMobile = useMediaQuery(theme.breakpoints.down(600));

  const handleClose = () => {
    setOpen(false);
  };
  const handleOpen = () => {
    setOpen(true);
  };
  const onAdornmentClick = () => {
    setOpen((old) => !old);
    if (isOpenEnd === true) {
      handleCloseEnd();
    }
  };

  const handleCloseEnd = () => {
    setOpenEnd(false);
  };
  const handleOpenEnd = () => {
    setOpenEnd(true);
  };
  const onAdornmentClickEnd = () => {
    setOpenEnd((old) => !old);
    if (isOpen === true) {
      handleClose();
    }
  };
  console.log("questions", questions);
  console.log("general", general);
  console.log("devices", devices);

  const now = moment();
  return (
    <>
      <HeaderFull isRequest />
      <SectionWrapper component={"section"} sx={{ padding: "60px 20px" }}>
        <Typography variant={"h4"}>Аналитика</Typography>
        <Box
          sx={{
            display: "flex",
            gap: isMobile ? "15px" : "20px",
            alignItems: "end",
            justifyContent: "space-between",
            padding: "40px 0 20px",
            borderBottom: `1px solid ${theme.palette.grey2.main}`,
          }}
        >
          <Box sx={{ display: "flex", gap: isMobile ? "15px" : "20px" }}>
            <Box>
              <Typography
                sx={{
                  fontSize: "16px",
                  marginBottom: "5px",
                  fontWeight: 500,
                  color: "4D4D4D",
                }}
              >
                Дата начала
              </Typography>
              <DatePicker
                open={isOpen}
                onClose={handleClose}
                onOpen={handleOpen}
                // defaultValue={now}
                sx={{
                  width: isMobile ? "146px" : "169px",

                  "& .MuiOutlinedInput-root": {
                    borderRadius: "10px",
                    fontSize: "16px",
                  },
                  "& .MuiInputBase-input": {
                    padding: "12.5px 14px",
                  },
                }}
                slotProps={{
                  textField: {
                    InputProps: {
                      endAdornment: (
                        <IconButton onClick={onAdornmentClick}>
                          <CalendarIcon />
                        </IconButton>
                      ),
                    },
                  },
                }}
                value={dayjs(from)}
                onChange={(newValue) => newValue && setFrom(newValue)}
              />
            </Box>
            <Box>
              <Typography
                sx={{
                  fontSize: "16px",
                  marginBottom: "5px",
                  fontWeight: 500,
                  color: "4D4D4D",
                }}
              >
                Дата окончания
              </Typography>
              <DatePicker
                open={isOpenEnd}
                onClose={handleCloseEnd}
                onOpen={handleOpenEnd}
                // defaultValue={now}
                sx={{
                  width: isMobile ? "146px" : "169px",
                  "& .MuiOutlinedInput-root": {
                    borderRadius: "10px",
                    fontSize: "16px",
                  },
                  "& .MuiInputBase-input": {
                    padding: "12.5px 14px",
                  },
                }}
                slotProps={{
                  textField: {
                    InputProps: {
                      endAdornment: (
                        <IconButton onClick={onAdornmentClickEnd}>
                          <CalendarIcon />
                        </IconButton>
                      ),
                    },
                  },
                }}
                value={dayjs(to)}
                onChange={(newValue) => newValue && setTo(newValue)}
              />
            </Box>
          </Box>

          <Button
            onClick={resetTime}
            variant="outlined"
            sx={{
              minWidth: isMobile ? "144px" : "180px",
              px: isMobile ? "31px" : "43px",
              color: theme.palette.brightPurple.main,
              "&:hover": {
                backgroundColor: "#581CA7",
                color: "#FFFFFF",
              },
              "&:active": {
                backgroundColor: "#000000",
                color: "#FFFFFF",
              },
            }}
          >
            Сбросить
          </Button>
        </Box>
        <General data={general} />
        <AnswersStatistics data={questions} />
        <Devices data={devices} />
      </SectionWrapper>
    </>
  );
}
