import { useState, useEffect } from "react";
import {
  Box,
  Button,
  FormControlLabel,
  Modal,
  Typography,
  useTheme,
  Checkbox,
} from "@mui/material";
import { isSameDay, isSameMonth, isSameYear, getHours } from "date-fns";

import { getQuestionByContentId } from "@root/questions/actions";
import { updateDeleteId } from "@root/uiTools/actions";
import { useUiTools } from "@root/uiTools/store";

import CheckboxIcon from "@icons/Checkbox";

type DeleteNodeModalProps = {
  removeNode?: (id: string) => void;
};

export const DeleteNodeModal = ({ removeNode }: DeleteNodeModalProps) => {
  const [skipModal, setSkipModal] = useState<boolean>(false);
  const { deleteNodeId } = useUiTools();
  const targetQuestion = getQuestionByContentId(deleteNodeId);
  const theme = useTheme();

  useEffect(() => {
    const isSkipModal = getIsSkipModal();

    if (isSkipModal) {
      deleteNode();
    }
  }, [deleteNodeId]);

  const getLastDeletionNodeTime = () =>
    Number(localStorage.getItem("lastDeletionNodeTime") || 0);

  const updateLastDeletionNodeTime = () => {
    const now = new Date().getTime();

    localStorage.setItem("lastDeletionNodeTime", String(now));
  };

  const getIsSkipModal = () => {
    const lastDeletionNodeTime = getLastDeletionNodeTime();
    const now = new Date().getTime();

    const sameYear = isSameYear(lastDeletionNodeTime, now);
    const sameMonth = isSameMonth(lastDeletionNodeTime, now);
    const sameDay = isSameDay(lastDeletionNodeTime, now);

    return sameYear && sameMonth && sameDay;
  };

  const deleteNode = () => {
    if (skipModal) {
      updateLastDeletionNodeTime();
    }

    if (deleteNodeId) {
      removeNode?.(deleteNodeId || "");
    }
    handleClose();
  };

  const handleClose = () => {
    updateDeleteId("");
  };

  return (
    <>
      <Modal open={!!deleteNodeId && !getIsSkipModal()} onClose={handleClose}>
        <Box
          sx={{
            outline: "none",
            position: "absolute",
            overflow: "hidden",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            maxWidth: "620px",
            width: "100%",
            bgcolor: "background.paper",
            borderRadius: "12px",
            boxShadow: 24,
            p: 0,
          }}
        >
          <Box
            sx={{
              boxSizing: "border-box",
              background: "#F2F3F7",
              height: "70px",
              padding: "0 25px",
              display: "flex",
              alignItems: "center",
            }}
          >
            <Typography component="span">{targetQuestion?.title}</Typography>
          </Box>
          <Typography sx={{ padding: "15px" }}>
            Вы правда хотите удалить этот узел? Данные его настроек и настроек
            его потомков будут утеряны.
          </Typography>
          <Box
            sx={{
              display: "flex",
              justifyContent: "end",
              gap: "10px",
              margin: "20px",
            }}
          >
            <Button
              variant="outlined"
              onClick={handleClose}
              sx={{ width: "100%", maxWidth: "130px" }}
            >
              Отмена
            </Button>
            <Button
              variant="contained"
              sx={{ width: "100%", maxWidth: "130px" }}
              onClick={deleteNode}
            >
              Удалить
            </Button>
          </Box>
          <FormControlLabel
            control={
              <Checkbox
                disableRipple
                icon={<CheckboxIcon />}
                checkedIcon={<CheckboxIcon checked />}
                onChange={(_, value) => setSkipModal(value)}
                checked={skipModal}
              />
            }
            label="Не спрашивать больше сегодня"
            sx={{
              userSelect: "none",
              margin: "0 0 10px",
              color: theme.palette.grey2.main,
            }}
          />
        </Box>
      </Modal>
    </>
  );
};
