import { Box, Button, ButtonBase, Link, Paper, Typography, useTheme } from "@mui/material";
import moment from "moment";
import React from "react";

import { QuizPreviewLayoutByType } from "./QuizPreviewLayoutByType";
import { OverTime } from "./OverTime";

import { useQuizStore } from "@/stores/useQuizStore";
import { useRootContainerSize } from "@contexts/RootContainerWidthContext";

import { useUADevice } from "@utils/hooks/useUADevice";
import { quizThemes } from "@utils/themes/Publication/themePublication";

import { NameplateLogo } from "@icons/NameplateLogo";
import { NameplateLogoDark } from "@icons/NameplateLogoDark";
import { useQuizViewStore } from "@/stores/quizView";
import { DESIGN_LIST } from "@/utils/designList";

import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
import QuizVideo from "@/ui_kit/VideoIframe/VideoIframe";

import { isProduction } from "@/utils/defineDomain";

export const StartPageViewPublication = () => {
  const theme = useTheme();
  const { settings, show_badge, quizId, questions } = useQuizStore();
  const { isMobileDevice } = useUADevice();
  const setCurrentQuizStep = useQuizViewStore((state) => state.setCurrentQuizStep);
  const [currentTime, setCurrentTime] = React.useState(moment());

  // Реактивный таймер для обновления времени
  React.useEffect(() => {
    const interval = setInterval(() => {
      setCurrentTime(moment());
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  const size = useRootContainerSize();
  const isMobile = size < 700;
  const isTablet = size >= 700 && size < 1100;

  const vkMetrics = useVkMetricsGoals(settings.cfg.vkMetricsNumber);
  const yandexMetrics = useYandexMetricsGoals(settings.cfg.yandexMetricsNumber);

  const handleCopyNumber = () => {
    navigator.clipboard.writeText(settings.cfg.info.phonenumber);

    vkMetrics.phoneNumberOpened();
    yandexMetrics.phoneNumberOpened();
  };

  const background =
    settings.cfg.startpage.background.type === "image" ? (
      <img
        src={settings.cfg.startpage.background.desktop || DESIGN_LIST[settings.cfg.theme] || ""}
        alt=""
        style={{
          display: "block",
          width: isMobile || settings.cfg.startpageType === "expanded" ? "100%" : undefined,
          height: "100%",
          minWidth: "100%",
          maxHeight: "100%",
          objectFit: "cover",
          overflow: "hidden",
        }}
      />
    ) : settings.cfg.startpage.background.type === "video" ? (
      settings.cfg.startpage.background.video ? (
        (() => {
          return (
            <QuizVideo
              videoUrl={settings.cfg.startpage.background.video}
              containerSX={{
                width: settings.cfg.startpageType === "centered" ? "550px" : "100%",
                height: settings.cfg.startpageType === "centered" ? "275px" : "100%",
                borderRadius: settings.cfg.startpageType === "centered" ? "10px" : "0",
                overflow: "hidden",
                "& iframe": {
                  width: "100%",
                  height: "100%",
                  transform:
                    settings.cfg.startpageType === "centered"
                      ? ""
                      : settings.cfg.startpageType === "expanded"
                        ? "scale(1.5)"
                        : "scale(2.4)",
                },
              }}
            />
          );
        })()
      ) : null
    ) : null;

  const quizHeaderBlock = (
    <Box
      sx={{
        margin: settings.cfg.startpageType === "centered" ? "0 auto" : null,
        display:
          isMobile && settings.cfg.startpage.position === "center" && settings.cfg.startpageType === "expanded"
            ? "flex"
            : "block",
        flexDirection: "column",
        alignItems: "center",
      }}
    >
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          flexWrap:
            settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center"
              ? "nowrap"
              : "wrap",
          gap: isMobile ? "20px" : "30px",
          mb:
            settings.cfg.startpageType === "centered"
              ? isMobile
                ? "20px"
                : "25px"
              : settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" && !isMobile
                ? 0
                : "7px",
          justifyContent:
            settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" && isMobile
              ? "center"
              : undefined,
        }}
        onClick={(event) => event.preventDefault()}
      >
        {settings.cfg.startpage.logo && (
          <img
            src={settings.cfg.startpage.logo}
            style={{
              maxHeight: isMobile ? "30px" : "40px",
              maxWidth: isMobile ? "100px" : "110px",
              objectFit: "cover",
            }}
            alt=""
          />
        )}
        <Typography
          sx={{
            fontSize: "12px",
            color: settings.cfg.startpageType === "expanded" ? "white" : theme.palette.text.primary,
            wordBreak:
              settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center"
                ? "normal"
                : "break-word",
          }}
        >
          {settings.cfg.info.orgname}
        </Typography>
      </Box>
      {((settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position !== "center") ||
        (isMobile && settings.cfg.startpageType === "expanded")) && <OverTime />}
    </Box>
  );

  const PenaBadge = (
    <Box
      component={Link}
      target={"_blank"}
      href={`https://${isProduction ? "" : "s"}quiz.pena.digital/answer/v1.0.0/logo?q=${quizId}`}
      sx={{
        display: "flex",
        alignItems: "center",
        gap: "7px",
        textDecoration: "none",
        mr:
          settings.cfg.startpageType === "expanded" &&
          settings.cfg.startpage.position === "center" &&
          !isTablet &&
          !isMobile
            ? "27px"
            : undefined,
      }}
    >
      {settings.cfg.startpageType === "expanded" ? (
        <NameplateLogo />
      ) : quizThemes[settings.cfg.theme].isLight ? (
        <NameplateLogoDark />
      ) : (
        <NameplateLogo />
      )}
    </Box>
  );

  const realQuestionsCount = questions.filter(
    (question) => question.type !== null && question.type !== "result"
  ).length;

  // Проверяем, истекло ли время для overTime
  const overTimeConfig = settings?.cfg?.overTime;
  const isOverTimeEnabled = overTimeConfig?.enabled;
  const isTimeExpired =
    isOverTimeEnabled && overTimeConfig?.endsAt
      ? currentTime.isAfter(moment(overTimeConfig.endsAt)) || currentTime.isSame(moment(overTimeConfig.endsAt))
      : false;

  const onQuizStart = () => {
    setCurrentQuizStep("question");

    vkMetrics.firstPageOpened();
    yandexMetrics.firstPageOpened();
  };

  const onSiteClick = () => {
    vkMetrics.emailOpened();
    yandexMetrics.emailOpened();

    setTimeout(() => {
      location.href = (
        settings.cfg.info.site.includes("https") ? settings.cfg.info.site : `https://${settings.cfg.info.site}`
      ).replace(/\s+/g, "");
    }, 1000);
  };

  return (
    <Paper
      className="settings-preview-draghandle"
      sx={{
        borderRadius: 0,
        height: "100%",
        width: "100%",
        background:
          settings.cfg.startpageType === "expanded"
            ? settings.cfg.startpage.position === "left" || (isMobile && settings.cfg.startpage.position === "right")
              ? "linear-gradient(90deg, rgba(39, 38, 38, 0.95) 7.66%, rgba(42, 42, 46, 0.85) 42.12%, rgba(51, 54, 71, 0.4) 100%)"
              : settings.cfg.startpage.position === "center"
                ? "linear-gradient(0deg, rgba(39, 38, 38, 0.95) 7.66%, rgba(42, 42, 46, 0.85) 42.12%, rgba(51, 54, 71, 0.4) 100%)"
                : "linear-gradient(-90deg, rgba(39, 38, 38, 0.95) 7.66%, rgba(42, 42, 46, 0.85) 42.12%, rgba(51, 54, 71, 0.4) 100%)"
            : theme.palette.background.default,

        color: settings.cfg.startpageType === "expanded" ? "white" : "black",
      }}
      onClick={(event) => event.preventDefault()}
    >
      <QuizPreviewLayoutByType
        quizHeaderBlock={quizHeaderBlock}
        quizMainBlock={
          <>
            <Box
              sx={{
                display: "flex",
                flexDirection: "column",
                justifyContent: settings.cfg.startpageType === "standard" && isMobile ? "start" : "center",
                flexGrow: settings.cfg.startpageType === "centered" ? 0 : 1,
                wordBreak: "break-word",
                alignItems:
                  settings.cfg.startpageType === "centered"
                    ? "center"
                    : settings.cfg.startpageType === "expanded"
                      ? settings.cfg.startpage.position === "center"
                        ? "center"
                        : "start"
                      : "start",
                marginTop: settings.cfg.startpageType === "centered" ? "30px" : isMobile ? "0px" : "5px",
                maxWidth: isMobile
                  ? "100%"
                  : settings.cfg.startpageType === "centered"
                    ? "700px"
                    : isTablet &&
                        settings.cfg.startpageType !== "expanded" &&
                        settings.cfg.startpage.position !== "center"
                      ? "380px"
                      : "531px",
              }}
            >
              <Typography
                sx={{
                  fontWeight: "700",
                  fontSize: isMobile ? "24px" : "27px",
                  fontStyle: "normal",
                  fontStretch: "normal",
                  lineHeight: isMobile ? "26.4px" : "normal",
                  overflowWrap: "break-word",
                  width: "100%",
                  textAlign:
                    settings.cfg.startpageType === "centered" || settings.cfg.startpage.position === "center"
                      ? "center"
                      : "-moz-initial",
                  color: settings.cfg.startpageType === "expanded" ? "white" : theme.palette.text.primary,
                }}
              >
                {settings.name}
              </Typography>
              <Typography
                sx={{
                  fontSize: isMobile ? "16px" : "17px",
                  fontWeight: "400",
                  lineHeight: isMobile ? "19.2px" : "normal",
                  margin: "12px 0 30px",
                  overflowWrap: "break-word",
                  width: "100%",
                  textAlign:
                    settings.cfg.startpageType === "centered" || settings.cfg.startpage.position === "center"
                      ? "center"
                      : "-moz-initial",
                  color: settings.cfg.startpageType === "expanded" ? "white" : theme.palette.text.primary,
                }}
              >
                {settings.cfg.startpage.description}
              </Typography>
              <Box width={settings.cfg.startpageType === "standard" ? "100%" : "auto"}>
                <Button
                  variant="contained"
                  disabled={realQuestionsCount === 0 || isTimeExpired}
                  sx={{
                    fontSize: "18px",
                    padding: "10px 20px",
                    width: "auto",
                    background: theme.palette.primary.main,
                    borderRadius: "12px",
                  }}
                  onClick={onQuizStart}
                >
                  {settings.cfg.startpage.button.trim() ? settings.cfg.startpage.button : "Пройти тест"}
                </Button>
              </Box>
            </Box>
            <Box
              sx={{
                display: "flex",
                flexGrow: settings.cfg.startpageType === "centered" ? (isMobile ? 0 : 1) : 0,
                gap: isMobile ? "30px" : "40px",
                alignItems: "flex-end",
                justifyContent:
                  (settings.cfg.startpageType === "expanded" &&
                    settings.cfg.startpage.position === "center" &&
                    isMobile) ||
                  (settings.cfg.startpageType === "centered" && isMobile)
                    ? "center"
                    : "space-between",
                width: "100%",
                flexWrap:
                  settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center"
                    ? isMobile
                      ? "wrap-reverse"
                      : "nowrap"
                    : "wrap",
              }}
            >
              {settings.cfg.startpageType === "expanded" &&
                settings.cfg.startpage.position === "center" &&
                !isMobile &&
                quizHeaderBlock}
              <Box
                sx={{
                  maxWidth: "300px",
                  display:
                    (settings.cfg.startpageType === "centered" && isMobile) ||
                    (settings.cfg.startpageType === "expanded" &&
                      settings.cfg.startpage.position === "center" &&
                      isMobile)
                      ? "flex"
                      : "block",
                  flexDirection: "column",
                  alignItems: "center",
                  order:
                    settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center"
                      ? "2"
                      : "0",
                }}
              >
                {((isMobile && settings.cfg.startpageType === "centered") ||
                  settings.cfg.startpageType === "standard") && (
                  <OverTime
                    sx={{
                      m: isMobile && settings.cfg.startpageType === "centered" ? "54px 0 20px" : "0",
                      ml: settings.cfg.startpageType === "standard" && !isMobile ? "100%" : "0",
                    }}
                  />
                )}
                {settings.cfg.info.site && (
                  <ButtonBase
                    onClick={onSiteClick}
                    sx={{
                      display: "block",
                      width: "100%",
                      marginTop: "10px",
                      marginLeft:
                        settings.cfg.startpageType === "expanded" &&
                        settings.cfg.startpage.position === "center" &&
                        !isMobile
                          ? "auto"
                          : undefined,
                    }}
                  >
                    <Typography
                      sx={{
                        lineHeight: "19px",
                        fontSize: "16px",
                        textAlign:
                          settings.cfg.startpageType === "expanded" &&
                          settings.cfg.startpage.position === "center" &&
                          !isMobile
                            ? "end"
                            : (settings.cfg.startpageType === "expanded" &&
                                  settings.cfg.startpage.position === "center" &&
                                  isMobile) ||
                                (settings.cfg.startpageType === "centered" && isMobile)
                              ? "center"
                              : "start",
                        color: theme.palette.primary.main,
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {settings.cfg.info.site}
                    </Typography>
                  </ButtonBase>
                )}
                {settings.cfg.info.clickable ? (
                  isMobileDevice ? (
                    <Link href={`tel:${settings.cfg.info.phonenumber}`}>
                      <Typography
                        sx={{
                          lineHeight: "19px",
                          textAlign:
                            settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center"
                              ? "end"
                              : "none",
                          fontSize: "16px",
                          color: settings.cfg.startpageType === "expanded" ? "#FFFFFF" : theme.palette.text.primary,
                        }}
                      >
                        {settings.cfg.info.phonenumber}
                      </Typography>
                    </Link>
                  ) : (
                    <ButtonBase
                      onClick={handleCopyNumber}
                      sx={{
                        display: "block",
                        marginTop: "10px",
                        marginLeft:
                          settings.cfg.startpageType === "expanded" &&
                          settings.cfg.startpage.position === "center" &&
                          !isMobile
                            ? "auto"
                            : undefined,
                      }}
                    >
                      <Typography
                        sx={{
                          textAlign:
                            settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center"
                              ? "end"
                              : "none",
                          fontSize: "16px",
                          lineHeight: "19px",
                          color: settings.cfg.startpageType === "expanded" ? "#FFFFFF" : theme.palette.text.primary,
                        }}
                      >
                        {settings.cfg.info.phonenumber}
                      </Typography>
                    </ButtonBase>
                  )
                ) : (
                  <Typography
                    sx={{
                      lineHeight: "19px",
                      textAlign:
                        settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center"
                          ? "end"
                          : "none",
                      fontSize: "16px",
                      marginTop: "10px",
                      color: settings.cfg.startpageType === "expanded" ? "#FFFFFF" : theme.palette.text.primary,
                    }}
                  >
                    {settings.cfg.info.phonenumber}
                  </Typography>
                )}

                <Typography
                  sx={{
                    lineHeight: "14px",
                    width: "100%",
                    overflowWrap: "break-word",
                    fontSize: "12px",
                    textAlign:
                      settings.cfg.startpageType === "expanded" &&
                      settings.cfg.startpage.position === "center" &&
                      !isMobile
                        ? "end"
                        : (settings.cfg.startpageType === "expanded" &&
                              settings.cfg.startpage.position === "center" &&
                              isMobile) ||
                            (settings.cfg.startpageType === "centered" && isMobile)
                          ? "center"
                          : "none",
                    maxHeight: "120px",
                    overflow: "auto",
                    marginTop: "10px",
                    "&::-webkit-scrollbar": { width: 0 },
                    color: settings.cfg.startpageType === "expanded" ? "white" : theme.palette.text.primary,
                  }}
                >
                  {settings.cfg.info.law}
                </Typography>
              </Box>
              <Box
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  gap: "16px",
                  alignItems: isMobile ? "center" : "end",
                }}
              >
                {((!isMobile && settings.cfg.startpageType === "centered") ||
                  (!isMobile &&
                    settings.cfg.startpageType === "expanded" &&
                    settings.cfg.startpage.position === "center")) && (
                  <OverTime
                    sx={{
                      ml:
                        !isMobile &&
                        settings.cfg.startpageType === "expanded" &&
                        settings.cfg.startpage.position === "center"
                          ? "91px"
                          : "0",
                    }}
                  />
                )}

                {show_badge && PenaBadge}
              </Box>
            </Box>
          </>
        }
        backgroundBlock={background}
        startpageType={settings.cfg.startpageType}
        alignType={settings.cfg.startpage.position}
      />
    </Paper>
  );
};
