import AlignCenterIcon from "@icons/AlignCenterIcon";
import AlignLeftIcon from "@icons/AlignLeftIcon";
import AlignRightIcon from "@icons/AlignRightIcon";
import ArrowDown from "@icons/ArrowDownIcon";
import ArrowLeft from "@icons/ArrowLeftSP";
import LayoutCenteredIcon from "@icons/LayoutCenteredIcon";
import LayoutExpandedIcon from "@icons/LayoutExpandedIcon";
import LayoutStandartIcon from "@icons/LayoutStandartIcon";

import MobilePhoneIcon from "@icons/MobilePhoneIcon";
import { QuizStartpageType } from "@model/quizSettings";
import InfoIcon from "@icons/InfoIcon";

import UploadBox from "@ui_kit/UploadBox";
import UploadIcon from "../../assets/icons/UploadIcon";

import {
  Box,
  Button,
  ButtonBase,
  Checkbox,
  FormControl,
  FormControlLabel,
  MenuItem,
  Select,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme,
} from "@mui/material";
import {
  incrementCurrentStep,
  updateQuiz,
  uploadQuizImage,
} from "@root/quizes/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import CustomCheckbox from "@ui_kit/CustomCheckbox";
import CustomTextField from "@ui_kit/CustomTextField";
import SelectableButton from "@ui_kit/SelectableButton";
import { StartPagePreview } from "@ui_kit/StartPagePreview";
import { resizeFavIcon } from "@ui_kit/reactImageFileResizer";
import { useState } from "react";
import { createPortal } from "react-dom";
import FaviconDropZone from "./FaviconDropZone";
import ModalSizeImage from "./ModalSizeImage";
import SelectableIconButton from "./SelectableIconButton";
import { DropZone } from "./dropZone";
import Extra from "./extra";
import TooltipClickInfo from "@ui_kit/Toolbars/TooltipClickInfo";

const designTypes = [
  [
    "standard",
    (color: string) => <LayoutStandartIcon color={color} />,
    "Standard",
  ],
  [
    "expanded",
    (color: string) => <LayoutExpandedIcon color={color} />,
    "Expanded",
  ],
  [
    "centered",
    (color: string) => <LayoutCenteredIcon color={color} />,
    "Centered",
  ],
] as const;
// type DesignType = typeof designTypes[number][0];

export default function StartPageSettings() {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down(650));
  const isSmallMonitor = useMediaQuery(theme.breakpoints.down(1500));
  const isTablet = useMediaQuery(theme.breakpoints.down(950));
  const quiz = useCurrentQuiz();
  const [formState, setFormState] = useState<"design" | "content">("design");
  const [mobileVersion, setMobileVersion] = useState(false);

  if (!quiz) return null;

  const MobileVersionHC = (bool: boolean) => {
    setMobileVersion(bool);
  };

  const designType = quiz?.config?.startpageType;

  const favIconDropZoneElement = (
    <FaviconDropZone
      imageUrl={quiz.config.startpage.favIcon}
      onImageUploadClick={async (file) => {
        const resizedImage = await resizeFavIcon(file);
        uploadQuizImage(quiz.id, resizedImage, (quiz, url) => {
          quiz.config.startpage.favIcon = url;
        });
      }}
      onDeleteClick={() => {
        updateQuiz(quiz.id, (quiz) => {
          quiz.config.startpage.favIcon = null;
        });
      }}
    />
  );

  return (
    <>
      <Typography
        variant="h5"
        sx={{ marginTop: "60px", marginBottom: isSmallMonitor ? "0" : "40px" }}
      >
        Стартовая страница
      </Typography>
      {isSmallMonitor && (
        <Box sx={{ display: "flex", gap: "5px", margin: "20px 0px 10px" }}>
          <Button onClick={() => setFormState("design")}>
            <Typography
              sx={{
                fontWeight: 500,
                fontSize: "16px",
                color: formState === "design" ? "#7E2AEA" : "#7D7E86",
                borderBottom:
                  formState === "design"
                    ? "2px solid #7E2AEA"
                    : "1px solid transparent",
              }}
            >
              Дизайн
            </Typography>
          </Button>
          <Button onClick={() => setFormState("content")}>
            <Typography
              sx={{
                fontWeight: 500,
                fontSize: "16px",
                color: formState === "content" ? "#7E2AEA" : "#7D7E86",
                borderBottom:
                  formState === "content"
                    ? "2px solid #7E2AEA"
                    : "1px solid transparent",
              }}
            >
              Контент
            </Typography>
          </Button>
        </Box>
      )}
      <Box
        sx={{
          boxSizing: "border-box",
          backgroundColor: "white",
          borderRadius: "12px",
          p: "20px",
          display: "flex",
          gap: "20px",
          maxWidth: "1160px",
          width: "100%",
          boxShadow: `0px 100px 309px rgba(210, 208, 225, 0.24),
                        0px 41.7776px 129.093px rgba(210, 208, 225, 0.172525),
                        0px 22.3363px 69.0192px rgba(210, 208, 225, 0.143066),
                        0px 12.5216px 38.6916px rgba(210, 208, 225, 0.12),
                        0px 6.6501px 20.5488px rgba(210, 208, 225, 0.0969343),
                        0px 2.76726px 8.55082px rgba(210, 208, 225, 0.0674749)`,
        }}
      >
        {(!isSmallMonitor || (isSmallMonitor && formState === "design")) && (
          <Box
            sx={{
              pr: "20px",
              borderRight: `1px solid ${
                isTablet ? "transparent" : theme.palette.grey2.main
              }`,
              display: "flex",
              flexDirection: "column",
              flex: `1 1 361px`,
            }}
          >
            <Typography
              sx={{
                fontWeight: 500,
                color: theme.palette.grey3.main,
                mb: "14px",
              }}
            >
              Дизайн
            </Typography>
            <FormControl
              fullWidth
              size="small"
              sx={{
                width: "100%",
                minWidth: "200px",
                height: "48px",
              }}
            >
              <Select
                id="category-select"
                variant="outlined"
                value={designType}
                displayEmpty
                onChange={(e) =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.startpageType = e.target
                      .value as QuizStartpageType;
                  })
                }
                sx={{
                  height: "48px",
                  borderRadius: "8px",
                  "& .MuiOutlinedInput-notchedOutline": {
                    border: `1px solid ${theme.palette.brightPurple.main} !important`,
                  },
                }}
                MenuProps={{
                  PaperProps: {
                    sx: {
                      mt: "8px",
                      p: "4px",
                      borderRadius: "8px",
                      border: "1px solid #EEE4FC",
                      boxShadow: "0px 8px 24px rgba(210, 208, 225, 0.4)",
                    },
                  },
                  MenuListProps: {
                    sx: {
                      py: 0,
                      display: "flex",
                      flexDirection: "column",
                      gap: "8px",
                      "& .Mui-selected": {
                        backgroundColor: theme.palette.background.default,
                        color: theme.palette.brightPurple.main,
                      },
                    },
                  },
                }}
                inputProps={{
                  sx: {
                    color: theme.palette.brightPurple.main,
                    display: "flex",
                    alignItems: "center",
                    px: "9px",
                    gap: "20px",
                  },
                }}
                IconComponent={(props) => <ArrowDown {...props} />}
              >
                {designTypes.map((type) => (
                  <MenuItem
                    key={type[0]}
                    value={type[0]}
                    sx={{
                      display: "flex",
                      alignItems: "center",
                      gap: "20px",
                      p: "4px",
                      borderRadius: "5px",
                      color: theme.palette.grey2.main,
                    }}
                  >
                    {type[1](
                      type[0] === designType
                        ? theme.palette.orange.main
                        : theme.palette.grey2.main,
                    )}
                    {type[2]}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <Typography
              sx={{
                fontWeight: 500,
                color: theme.palette.grey3.main,
                mt: "20px",
                mb: "14px",
              }}
            >
              Фон
            </Typography>
            <Box
              sx={{
                display: "flex",
                gap: "10px",
              }}
            >
              <SelectableButton
                isSelected={quiz.config.startpage.background.type === "image"}
                onClick={() =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.startpage.background.type = "image";
                  })
                }
              >
                Изображение
              </SelectableButton>
              <SelectableButton
                isSelected={quiz.config.startpage.background.type === "video"}
                onClick={() =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.startpage.background.type = "video";
                  })
                }
              >
                Видео
              </SelectableButton>
            </Box>

            {quiz.config.startpage.background.type === "image" && (
              <Box
                sx={{
                  display:
                    quiz.config.startpage.background.type === "image"
                      ? "flex"
                      : "none",
                  flexDirection: "column",
                }}
              >
                <Box
                  sx={{
                    display: mobileVersion ? "none" : "flex",
                    flexDirection: "column",
                  }}
                >
                  <Typography
                    sx={{
                      fontWeight: 500,
                      color: theme.palette.grey3.main,
                      mt: "20px",
                      mb: "14px",
                    }}
                  >
                    Изображение
                  </Typography>
                  <DropZone
                    value={"5 MB максимум"}
                    sx={{ maxWidth: "300px" }}
                    imageUrl={quiz.config.startpage.background.desktop}
                    originalImageUrl={
                      quiz.config.startpage.background.originalDesktop
                    }
                    onImageUploadClick={(file) => {
                      uploadQuizImage(quiz.id, file, (quiz, url) => {
                        quiz.config.startpage.background.desktop = url;
                        quiz.config.startpage.background.originalDesktop = url;
                      });
                    }}
                    onImageSaveClick={(file) => {
                      uploadQuizImage(quiz.id, file, (quiz, url) => {
                        quiz.config.startpage.background.desktop = url;
                      });
                    }}
                    onDeleteClick={() => {
                      updateQuiz(quiz.id, (quiz) => {
                        quiz.config.startpage.background.desktop = null;
                      });
                    }}
                  />
                </Box>

                <ModalSizeImage />
              </Box>
            )}

            {quiz.config.startpage.background.type === "video" && (
              <>
                <Box
                  sx={{
                    display: "flex",
                    alignItems: "center",
                    gap: "7px",
                    mt: "20px",
                    mb: "14px",
                  }}
                >
                  <Typography
                    sx={{ fontWeight: 500, color: theme.palette.grey3.main }}
                  >
                    Добавить видео
                  </Typography>
                  {isMobile ? (
                    <TooltipClickInfo title={"Можно загрузить видео."} />
                  ) : (
                    <Tooltip title="Можно загрузить видео." placement="top">
                      <Box>
                        <InfoIcon />
                      </Box>
                    </Tooltip>
                  )}
                </Box>
                <ButtonBase
                  component="label"
                  sx={{
                    justifyContent: "center",
                    height: "48px",
                    width: "48px",
                    display: "flex",
                    alignItems: "center",
                    my: "20px",
                  }}
                >
                  <input
                    onChange={(event) => {
                      const file = event.target.files?.[0];
                      if (file) {
                        uploadQuizImage(quiz.id, file, (quiz, url) => {
                          quiz.config.startpage.background.video = url;
                        });
                        // setVideo(URL.createObjectURL(file));
                      }
                    }}
                    hidden
                    accept=".mp4"
                    multiple
                    type="file"
                  />
                  <UploadBox
                    icon={<UploadIcon />}
                    sx={{
                      height: "48px",
                      width: "48px",
                    }}
                  />
                </ButtonBase>
                {quiz.config.startpage.background.video ? (
                  <video
                    src={quiz.config.startpage.background.video}
                    width="400"
                    controls
                  />
                ) : null}
              </>
            )}
            {designType !== "centered" && (
              <>
                <Typography
                  sx={{
                    fontWeight: 500,
                    color: theme.palette.grey3.main,
                    mt: "20px",
                    mb: "14px",
                  }}
                >
                  Расположение элементов
                </Typography>
                <Box
                  sx={{
                    display: "flex",
                    gap: "10px",
                  }}
                >
                  <SelectableIconButton
                    onClick={() =>
                      updateQuiz(quiz.id, (quiz) => {
                        quiz.config.startpage.position = "left";
                      })
                    }
                    isActive={quiz.config.startpage.position === "left"}
                    Icon={AlignLeftIcon}
                  />
                  <SelectableIconButton
                    onClick={() =>
                      updateQuiz(quiz.id, (quiz) => {
                        quiz.config.startpage.position = "center";
                      })
                    }
                    isActive={quiz.config.startpage.position === "center"}
                    Icon={AlignCenterIcon}
                    sx={{
                      display: designType === "standard" ? "none" : "flex",
                    }}
                  />
                  <SelectableIconButton
                    onClick={() =>
                      updateQuiz(quiz.id, (quiz) => {
                        quiz.config.startpage.position = "right";
                      })
                    }
                    isActive={quiz.config.startpage.position === "right"}
                    Icon={AlignRightIcon}
                  />
                </Box>
              </>
            )}
            {(isTablet || !isSmallMonitor) && (
              <>
                <Box
                  sx={{
                    display:
                      quiz.config.startpage.background.type === "image"
                        ? "flex"
                        : "none",
                    flexDirection: "column",
                  }}
                >
                  <Typography
                    sx={{
                      fontWeight: 500,
                      color: theme.palette.grey3.main,
                      margin: "20px 0",
                    }}
                  >
                    Логотип
                  </Typography>
                  <DropZone
                    value={"5 MB максимум"}
                    sx={{ maxWidth: "300px" }}
                    imageUrl={quiz.config.startpage.logo}
                    originalImageUrl={quiz.config.startpage.originalLogo}
                    onImageUploadClick={(file) => {
                      uploadQuizImage(quiz.id, file, (quiz, url) => {
                        quiz.config.startpage.logo = url;
                        quiz.config.startpage.originalLogo = url;
                      });
                    }}
                    onImageSaveClick={(file) => {
                      uploadQuizImage(quiz.id, file, (quiz, url) => {
                        quiz.config.startpage.logo = url;
                      });
                    }}
                    onDeleteClick={() => {
                      updateQuiz(quiz.id, (quiz) => {
                        quiz.config.startpage.logo = null;
                      });
                    }}
                  />
                </Box>

                <Typography
                  sx={{
                    fontWeight: 500,
                    color: theme.palette.grey3.main,
                    mt: "20px",
                    mb: "14px",
                  }}
                >
                  Favicon
                </Typography>
                {favIconDropZoneElement}
              </>
            )}
          </Box>
        )}
        {/*Правая сторона*/}
        <Box
          sx={{
            display: isTablet && formState === "design" ? "none" : "flex",
            flexDirection: "column",
            flex: `1 1 795px`,
          }}
        >
          {!isTablet && isSmallMonitor && formState === "design" && (
            <>
              <Box
                sx={{
                  display:
                    quiz.config.startpage.background.type === "image"
                      ? "flex"
                      : "none",
                  flexDirection: "column",
                }}
              >
                <Typography
                  sx={{
                    fontWeight: 500,
                    color: theme.palette.grey3.main,
                    marginBottom: "15px",
                  }}
                >
                  Логотип
                </Typography>
                <DropZone
                  value={"5 MB максимум"}
                  sx={{ maxWidth: "300px" }}
                  imageUrl={quiz.config.startpage.logo}
                  originalImageUrl={quiz.config.startpage.originalLogo}
                  onImageUploadClick={(file) => {
                    uploadQuizImage(quiz.id, file, (quiz, url) => {
                      quiz.config.startpage.logo = url;
                      quiz.config.startpage.originalLogo = url;
                    });
                  }}
                  onImageSaveClick={(file) => {
                    uploadQuizImage(quiz.id, file, (quiz, url) => {
                      quiz.config.startpage.logo = url;
                    });
                  }}
                  onDeleteClick={() => {
                    updateQuiz(quiz.id, (quiz) => {
                      quiz.config.startpage.logo = null;
                    });
                  }}
                />
              </Box>

              <Typography
                sx={{
                  fontWeight: 500,
                  color: theme.palette.grey3.main,
                  mt: "20px",
                  mb: "14px",
                }}
              >
                Favicon
              </Typography>
              {favIconDropZoneElement}
            </>
          )}
          {(!isSmallMonitor || (isSmallMonitor && formState === "content")) && (
            <>
              <Typography
                sx={{
                  fontWeight: 500,
                  color: theme.palette.grey3.main,
                  mb: "14px",
                }}
              >
                Заголовок
              </Typography>
              <CustomTextField
                placeholder="Имя заголовка опроса для подбора табуретки"
                value={quiz.name}
                onChange={(e) =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.name = e.target.value;
                  })
                }
                maxLength={40}
              />
              <Typography
                sx={{
                  fontWeight: 500,
                  color: theme.palette.grey3.main,
                  mt: "20px",
                  mb: "14px",
                }}
              >
                Текст
              </Typography>
              <CustomTextField
                placeholder="Внимательно заполняйте поля ответов"
                value={quiz.config.startpage.description}
                onChange={(e) =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.startpage.description = e.target.value;
                  })
                }
                maxLength={70}
              />
              <Typography
                sx={{
                  fontWeight: 500,
                  color: theme.palette.grey3.main,
                  mt: "20px",
                  mb: "14px",
                }}
              >
                Текст кнопки
              </Typography>
              <CustomTextField
                placeholder="Начать опрос"
                value={quiz.config.startpage.button}
                onChange={(e) =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.startpage.button = e.target.value;
                  })
                }
                maxLength={15}
              />
              <Typography
                sx={{
                  fontWeight: 500,
                  color: theme.palette.grey3.main,
                  mt: "20px",
                  mb: "14px",
                }}
              >
                Телефон
              </Typography>
              <CustomTextField
                placeholder="8-800-000-00-00"
                type="number"
                value={quiz.config.info.phonenumber}
                onChange={(e) =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.info.phonenumber = e.target.value;
                  })
                }
                maxLength={20}
              />
              <CustomCheckbox
                sx={{ margin: "10px 0" }}
                label="Кликабельный"
                checked={quiz.config.info.clickable}
                handleChange={(e) =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.info.clickable = e.target.checked;
                  })
                }
              />
              <Typography
                sx={{
                  fontWeight: 500,
                  color: theme.palette.grey3.main,
                  mt: "11px",
                  mb: "14px",
                }}
              >
                Название или слоган компании
              </Typography>
              <CustomTextField
                placeholder="Только лучшее"
                value={quiz.config.info.orgname}
                onChange={(e) =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.info.orgname = e.target.value;
                  })
                }
                maxLength={25}
              />
              <Typography
                sx={{
                  fontWeight: 500,
                  color: theme.palette.grey3.main,
                  mt: "20px",
                  mb: "14px",
                }}
              >
                Сайт
              </Typography>
              <CustomTextField
                placeholder="https://mysite.com"
                value={quiz.config.info.site}
                onChange={(e) =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.info.site = e.target.value;
                  })
                }
                maxLength={25}
              />
              <Typography
                sx={{
                  fontWeight: 500,
                  color: theme.palette.grey3.main,
                  mt: "20px",
                  mb: "14px",
                }}
              >
                Юридическая информация
              </Typography>
              <CustomTextField
                placeholder="Данные наших документов"
                value={quiz.config.info.law}
                onChange={(e) =>
                  updateQuiz(quiz.id, (quiz) => {
                    quiz.config.info.law = e.target.value;
                  })
                }
                maxLength={45}
              />
              <Extra />
            </>
          )}
        </Box>
      </Box>
      {isSmallMonitor && (
        <Box sx={{ maxWidth: "1160px", marginBottom: "60px" }}>
          {formState === "content" && (
            <Button
              onClick={() => setFormState("design")}
              sx={{
                display: "flex",
                marginTop: "20px",
                padding: "0",
                fontWeight: "bold",
                fontSize: "16px",
                color: "#7E2AEA",
                textDecoration: "underline",
                textUnderlineOffset: "2px",
              }}
            >
              <ArrowLeft right={false} /> Вернуться к дизайну
            </Button>
          )}
          {formState === "design" && (
            <Button
              onClick={() => setFormState("content")}
              sx={{
                display: "flex",
                marginLeft: "auto",
                marginTop: "20px",
                padding: "0",
                fontWeight: "bold",
                fontSize: "16px",
                color: "#7E2AEA",
                textDecoration: "underline",
                textUnderlineOffset: "2px",
              }}
            >
              Далее заполнить контент <ArrowLeft right={true} />
            </Button>
          )}
        </Box>
      )}
      <Box
        sx={{
          maxWidth: "1160px",
          display: "flex",
          gap: "20px",
          justifyContent: "flex-end",
          flexDirection: isTablet ? "column" : "row",
          marginTop: "30px",
          marginBottom: isTablet ? "90px" : undefined,
        }}
      >
        <FormControlLabel
          control={
            <Checkbox
              icon={
                <Button
                  variant="outlined"
                  sx={{
                    backgroundColor: "transparent",
                    color: theme.palette.brightPurple.main,
                  }}
                >
                  Отключить стартовую страницу
                </Button>
              }
              checkedIcon={
                <Button
                  variant="outlined"
                  sx={{
                    backgroundColor: theme.palette.brightPurple.main,
                    color: "white",
                  }}
                >
                  Включить стартовую страницу
                </Button>
              }
              sx={{
                borderRadius: 0,
                padding: 0,
              }}
              onChange={(e) =>
                updateQuiz(quiz.id, (quiz) => {
                  quiz.config.noStartPage = e.target.checked;
                })
              }
              checked={quiz.config.noStartPage}
            />
          }
          label=""
          sx={{
            color: theme.palette.brightPurple.main,
            margin: "0",
            userSelect: "none",
            justifyContent: "flex-end",
          }}
        />
        <Button
          variant="contained"
          data-cy="setup-questions"
          onClick={incrementCurrentStep}
        >
          Настроить вопросы
        </Button>
      </Box>
      {createPortal(<StartPagePreview />, document.body)}
    </>
  );
}

function IconCheck() {
  return (
    <Box
      sx={{
        height: "36px",
        width: "36px",
        borderRadius: "8px",
        backgroundColor: "#EEE4FC",
      }}
    />
  );
}
