import {
  Button,
  Dialog,
  IconButton,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import Box from "@mui/material/Box";
import CloseIcon from "@mui/icons-material/Close";
import React, { useEffect, useMemo, useState } from "react";
import CustomTextField from "@ui_kit/CustomTextField";
import EditPencil from "@icons/EditPencil";
import Trash from "@icons/trash";
import { updateQuiz } from "@root/quizes/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { QuizMetricType } from "@model/quizSettings";
import { InstructionsBlock } from "./IntsructionsBlock/InstructionsBlock";
import { YandexInstruction } from "./IntsructionsBlock/Instructions/YandexInstruction";
import { VKPixelInstruction } from "./IntsructionsBlock/Instructions/VKInstruction";

interface Props {
  isModalOpen: boolean;
  handleCloseModal: () => void;
  companyName: keyof typeof QuizMetricType;
}

export const AnalyticsModal = ({
  isModalOpen,
  handleCloseModal,
  companyName,
}: Props) => {
  const theme = useTheme();
  const quiz = useCurrentQuiz();
  const isMobile = useMediaQuery(theme.breakpoints.down(600));
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const configName = QuizMetricType[companyName];
  const meterNumber = quiz?.config[configName];
  const [isSave, setIsSave] = useState<boolean>(!!meterNumber);
  const [currentValue, setCurrentValue] = useState<string>(
    meterNumber ? meterNumber.toString() : "",
  );
  const analyticTexts = useMemo(() => {
    return {
      yandex: {
        header: "Яндекс.Метрикой",
        counterName: "счетчика",
        instructionTitle: "Как установить Яндекс Метрику в квиз?",
        instructionSubTitle: "Инструкция по настройке Яндекс Метрики",
        instructionHeader: "Настройка счётчика и интеграции",
        instructionText: <YandexInstruction />,
      },
      vk: {
        header: "VK Пиксель",
        counterName: "пикселя",
        instructionTitle: "Как установить VK Пиксель в квиз?",
        instructionSubTitle: "Инструкция по настройке VK Пиксель",
        instructionHeader: "Настройка счётчика и интеграции",
        instructionText: <VKPixelInstruction />,
      },
    };
  }, []);

  const handleClose = () => {
    handleCloseModal();
    if (!meterNumber) {
      setIsSave(false);
      setCurrentValue("");
      return;
    }
    setIsSave(true);
    setCurrentValue(meterNumber.toString());
  };
  const handleSave = () => {
    handleCloseModal();
    updateQuiz(quiz?.id, (quiz) => {
      quiz.config[configName] = currentValue ? Number(currentValue) : undefined;
    });
    if (!currentValue) {
      setIsSave(false);
      return;
    }
    setIsSave(true);
  };
  const handleEdit = () => {
    setIsSave(false);
  };

  const handleClear = () => {
    setCurrentValue("");
    setIsSave(false);
  };

  useEffect(() => {
    const configName =
      QuizMetricType[companyName as keyof typeof QuizMetricType];
    const meterNumber = quiz?.config[configName];
    setCurrentValue(meterNumber ? meterNumber.toString() : "");
    setIsSave(!!meterNumber);
  }, [companyName]);

  return (
    <Dialog
      open={isModalOpen}
      onClose={handleClose}
      fullWidth
      PaperProps={{
        sx: {
          maxWidth: isTablet ? "100%" : "920px",
          borderRadius: "12px",
        },
      }}
    >
      <Box
        sx={{
          width: "100%",
          height: "68px",
          backgroundColor: theme.palette.background.default,
        }}
      >
        <Typography
          sx={{
            fontSize: isMobile ? "20px" : "24px",
            fontWeight: "500",
            padding: "20px",
            color: theme.palette.grey2.main,
          }}
        >
          Аналитика с {analyticTexts[companyName]?.header}
        </Typography>
      </Box>
      <IconButton
        onClick={handleClose}
        sx={{
          width: "12px",
          height: "12px",
          position: "absolute",
          right: "15px",
          top: "15px",
        }}
      >
        <CloseIcon
          sx={{ width: "12px", height: "12px", transform: "scale(1.5)" }}
        />
      </IconButton>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          padding: "20px 20px",
          flexGrow: 1,
          gap: "20px",
        }}
      >
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            gap: "10px",
          }}
        >
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              maxWidth: isMobile ? "100%" : "590px",
              position: "relative",
            }}
          >
            <Typography fontWeight={500}>
              {isSave
                ? `Ваш номер ${analyticTexts[companyName]?.counterName}`
                : `Введите номер ${analyticTexts[companyName]?.counterName}`}
            </Typography>
            {isSave && (
              <Box
                sx={{
                  display: "flex",
                  gap: "10px",
                  position: "absolute",
                  right: "0",
                  top: "0",
                }}
              >
                <IconButton onClick={handleEdit} sx={{ padding: "0" }}>
                  <EditPencil
                    color={theme.palette.brightPurple.main}
                    width={"24px"}
                    height={"24px"}
                  />
                </IconButton>
                <IconButton onClick={handleClear} sx={{ padding: "0" }}>
                  <Trash
                    sx={{
                      width: "24px",
                      "& path": {
                        stroke: theme.palette.brightPurple.main,
                      },
                    }}
                  />
                </IconButton>
              </Box>
            )}
          </Box>
          <Box
            sx={{
              display: "flex",
              flexDirection: isMobile ? "column" : "row",
              gap: "20px",
              alignItems: "center",
            }}
          >
            <CustomTextField
              sxForm={{ maxWidth: isMobile ? "100%" : "590px" }}
              placeholder={isSave ? currentValue : "в формате ХХХХХХХХ"}
              type={"number"}
              value={currentValue}
              disabled={isSave}
              onChange={(e) => {
                const onlyNums = e.target.value.replace(/[^0-9]/g, "");
                setCurrentValue(onlyNums);
              }}
            />
            {!isSave && (
              <Box
                sx={{
                  width: isMobile ? "100%" : "auto",
                  display: "flex",
                  justifyContent: isMobile ? "space-between" : "end",
                  gap: "10px",
                }}
              >
                {meterNumber && !isSave && (
                  <Button
                    sx={{ width: isMobile ? "100%" : "130px", height: "44px" }}
                    onClick={handleClose}
                    variant={"outlined"}
                  >
                    Отмена
                  </Button>
                )}
                <Button
                  sx={{ width: isMobile ? "100%" : "130px", height: "44px" }}
                  variant={"contained"}
                  onClick={handleSave}
                >
                  Сохранить
                </Button>
              </Box>
            )}
          </Box>
        </Box>
        <InstructionsBlock
          headerText={analyticTexts[companyName]?.instructionTitle}
          subHeaderText={analyticTexts[companyName]?.instructionSubTitle}
          instructionTitle={analyticTexts[companyName]?.instructionHeader}
          instructionsText={analyticTexts[companyName]?.instructionText}
        />
      </Box>
    </Dialog>
  );
};
