import AlignCenterIcon from "@icons/AlignCenterIcon";
import AlignLeftIcon from "@icons/AlignLeftIcon";
import AlignRightIcon from "@icons/AlignRightIcon";
import ArrowDown from "@icons/ArrowDownIcon";
import InfoIcon from "@icons/InfoIcon";
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 {
    Box,
    Button,
    ButtonBase,
    Checkbox,
    FormControl,
    FormControlLabel,
    MenuItem,
    Select,
    Tooltip,
    Typography,
    useMediaQuery,
    useTheme,
} from "@mui/material";
import { incrementCurrentStep, updateQuiz } 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 UploadBox from "@ui_kit/UploadBox";
import { useState } from "react";
import { createPortal } from "react-dom";
import UploadIcon from "../../assets/icons/UploadIcon";
import ModalSizeImage from "./ModalSizeImage";
import SelectableIconButton from "./SelectableIconButton";
import { DropZone } from "./dropZone";
import DropFav from "./dropfavicon";
import Extra from "./extra";


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 isSmallMonitor = useMediaQuery(theme.breakpoints.down(1500));
    const isTablet = useMediaQuery(theme.breakpoints.down(950));
    const quiz = useCurrentQuiz();
    const [formState, setFormState] = useState<"design" | "content">("design");

    const designType = quiz?.config?.startpageType;

    const videoHC = (videoInp: HTMLInputElement) => {
        const file = videoInp.files?.[0];

        if (file) {
            setVideo(URL.createObjectURL(file));
        }
    };

    const [video, setVideo] = useState("");

    const [mobileVersion, setMobileVersion] = useState(false);
    const MobileVersionHC = (bool: boolean) => {
        setMobileVersion(bool);
    };

    if (!quiz) return null; // TODO throw and catch with error boundary

    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>

                        <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
                                    text={"5 MB максимум"}
                                    heightImg={"110px"}
                                    sx={{ maxWidth: "300px" }}
                                    imageUrl={quiz.config.startpage.background.desktop}
                                    onImageUpload={(quiz, url) => {
                                        quiz.config.startpage.background.desktop = url;
                                    }}
                                />
                            </Box>

                            <ModalSizeImage />

                            <Box
                                sx={{
                                    mt: "10px",
                                    display: "flex",
                                    gap: "10px",
                                    flexDirection: "column",
                                }}
                            >
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            icon={<IconCheck />}
                                            checkedIcon={<MobilePhoneIcon bgcolor={"#EEE4FC"} />}
                                        />
                                    }
                                    label="мобильная версия"
                                    sx={{
                                        color: theme.palette.brightPurple.main,
                                        textDecorationLine: "underline",
                                        textDecorationColor: theme.palette.brightPurple.main,
                                        ml: "-9px",
                                        userSelect: "none",
                                        "& .css-14o5ia4-MuiTypography-root": {
                                            fontSize: "16px"
                                        }
                                    }}
                                    onClick={() => {
                                        MobileVersionHC(!mobileVersion);
                                    }}
                                />
                                {mobileVersion ? (
                                    <Box sx={{ display: "flex", flexDirection: "column" }}>
                                        <Typography
                                            sx={{
                                                fontWeight: 500,
                                                color: theme.palette.grey3.main,
                                                mt: "11px",
                                                mb: "14px",
                                            }}
                                        >
                                            Изображение для мобильной версии
                                        </Typography>
                                        <DropZone
                                            text={"5 MB максимум"}
                                            heightImg={"110px"}
                                            imageUrl={quiz.config.startpage.background.mobile}
                                            onImageUpload={(quiz, url) => {
                                                quiz.config.startpage.background.mobile = url;
                                            }}
                                        />
                                    </Box>
                                ) : (
                                    <></>
                                )}
                            </Box>
                        </Box>

                        <Box
                            sx={{
                                display: quiz.config.startpage.background.type === "image" ? "none" : "flex",
                                flexDirection: "column",
                            }}
                        >
                            <Box
                                sx={{
                                    display: "flex",
                                    alignItems: "center",
                                    gap: "7px",
                                    mt: "20px",
                                    mb: "14px",
                                }}
                            >
                                <Typography
                                    sx={{ fontWeight: 500, color: theme.palette.grey3.main }}
                                >
                                    Добавить видео
                                </Typography>
                                <Tooltip title="Можно загрузить видео." placement="top">
                                    <Box>
                                        <InfoIcon />
                                    </Box>
                                </Tooltip>
                            </Box>
                            <ButtonBase
                                component="label"
                                sx={{ justifyContent: "flex-start" }}
                            >
                                <input
                                    onChange={(event) => videoHC(event.target)}
                                    hidden
                                    accept=".mp4"
                                    multiple
                                    type="file"
                                />
                                <UploadBox
                                    icon={<UploadIcon />}
                                    sx={{
                                        height: "48px",
                                        width: "48px",
                                        marginBottom: "20px",
                                    }}
                                />
                            </ButtonBase>
                            {video ? <video src={video} width="400" controls /> : null}
                            <Typography
                                sx={{
                                    fontWeight: 500,
                                    color: theme.palette.grey3.main,
                                    mt: "20px",
                                    mb: "5px",
                                }}
                            >
                                Настройки видео
                            </Typography>
                            <CustomCheckbox
                                label="Зацикливать видео"
                                checked={quiz.config.startpage.background.cycle}
                                handleChange={e => updateQuiz(quiz.id, quiz => {
                                    quiz.config.startpage.background.cycle = e.target.checked;
                                })}
                            />
                            <Typography
                                sx={{
                                    fontWeight: 500,
                                    color: theme.palette.grey3.main,
                                    mt: "11px",
                                    mb: "14px",
                                }}
                            >
                                Изображение для мобильной версии
                            </Typography>
                            <DropZone
                                text={"5 MB максимум"}
                                heightImg={"110px"}
                                imageUrl={quiz.config.startpage.background.mobile}
                                onImageUpload={(quiz, url) => {
                                    quiz.config.startpage.background.mobile = url;
                                }}
                            />
                        </Box>

                        <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 === "centered" ? "flex" : "none" }}
                            />
                            <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
                                        text={"5 MB максимум"}
                                        heightImg={"110px"}
                                        sx={{ maxWidth: "300px" }}
                                        imageUrl={quiz.config.logo}
                                        onImageUpload={(quiz, url) => {
                                            quiz.config.logo = url;
                                        }}
                                    />
                                </Box>

                                <Typography
                                    sx={{
                                        fontWeight: 500,
                                        color: theme.palette.grey3.main,
                                        mt: "20px",
                                        mb: "14px",
                                    }}
                                >
                                    Favicon
                                </Typography>
                                <Box
                                    sx={{
                                        display: "flex",
                                        alignItems: "end",
                                        gap: "10px",
                                    }}
                                >
                                    <DropFav
                                        sx={{ height: "48px", width: "48px" }}
                                        heightImg={"48px"}
                                        widthImg={"48px"}
                                    />

                                    <Typography
                                        sx={{
                                            color: theme.palette.orange.main,
                                            fontSize: "16px",
                                            lineHeight: "19px",
                                            textDecoration: "underline",
                                        }}
                                    >
                                        5 MB максимум
                                    </Typography>
                                </Box>
                            </>
                        )}
                    </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
                                    text={"5 MB максимум"}
                                    heightImg={"110px"}
                                    sx={{ maxWidth: "300px" }}
                                    imageUrl={quiz.config.logo}
                                    onImageUpload={(quiz, url) => {
                                        quiz.config.logo = url;
                                    }}
                                />
                            </Box>

                            <Typography
                                sx={{
                                    fontWeight: 500,
                                    color: theme.palette.grey3.main,
                                    mt: "20px",
                                    mb: "14px",
                                }}
                            >
                                Favicon
                            </Typography>
                            <Box
                                sx={{
                                    display: "flex",
                                    alignItems: "end",
                                    gap: "10px",
                                }}
                            >
                                <DropFav
                                    sx={{ height: "48px", width: "48px" }}
                                    heightImg={"48px"}
                                    widthImg={"48px"}
                                />

                                <Typography
                                    sx={{
                                        color: theme.palette.orange.main,
                                        fontSize: "16px",
                                        lineHeight: "19px",
                                        textDecoration: "underline",
                                    }}
                                >
                                    5 MB максимум
                                </Typography>
                            </Box>
                        </>
                    )}
                    {(!isSmallMonitor || (isSmallMonitor && formState === "content")) && (
                        <>
                            <Typography
                                sx={{
                                    fontWeight: 500,
                                    color: theme.palette.grey3.main,
                                    mb: "14px",
                                }}
                            >
                                Заголовок
                            </Typography>
                            <CustomTextField
                                placeholder="Имя заголовка об опроснике для подбора табуретки"
                                text={quiz.name}
                                onChange={e => updateQuiz(quiz.id, quiz => {
                                    quiz.name = e.target.value;
                                })}
                            />
                            <Typography
                                sx={{
                                    fontWeight: 500,
                                    color: theme.palette.grey3.main,
                                    mt: "20px",
                                    mb: "14px",
                                }}
                            >
                                Текст
                            </Typography>
                            <CustomTextField
                                placeholder="Внимательно заполняйте поля ответов"
                                text={quiz.config.startpage.description}
                                onChange={e => updateQuiz(quiz.id, quiz => {
                                    quiz.config.startpage.description = e.target.value;
                                })}
                            />
                            <Typography
                                sx={{
                                    fontWeight: 500,
                                    color: theme.palette.grey3.main,
                                    mt: "20px",
                                    mb: "14px",
                                }}
                            >
                                Текст кнопки
                            </Typography>
                            <CustomTextField
                                placeholder="Начать опрос"
                                text={quiz.config.startpage.button}
                                onChange={e => updateQuiz(quiz.id, quiz => {
                                    quiz.config.startpage.button = e.target.value;
                                })}
                            />
                            <Typography
                                sx={{
                                    fontWeight: 500,
                                    color: theme.palette.grey3.main,
                                    mt: "20px",
                                    mb: "14px",
                                }}
                            >
                                Телефон
                            </Typography>
                            <CustomTextField
                                placeholder="8-800-000-00-00"
                                text={quiz.config.info.phonenumber}
                                onChange={e => updateQuiz(quiz.id, quiz => {
                                    quiz.config.info.phonenumber = e.target.value;
                                })}
                            />
                            <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="Только лучшее"
                                text={quiz.config.info.orgname}
                                onChange={e => updateQuiz(quiz.id, quiz => {
                                    quiz.config.info.orgname = e.target.value;
                                })}
                            />
                            <Typography
                                sx={{
                                    fontWeight: 500,
                                    color: theme.palette.grey3.main,
                                    mt: "20px",
                                    mb: "14px",
                                }}
                            >
                                Сайт
                            </Typography>
                            <CustomTextField
                                placeholder="https://mysite.com"
                                text={quiz.config.info.site}
                                onChange={e => updateQuiz(quiz.id, quiz => {
                                    quiz.config.info.site = e.target.value;
                                })}
                            />
                            <Typography
                                sx={{
                                    fontWeight: 500,
                                    color: theme.palette.grey3.main,
                                    mt: "20px",
                                    mb: "14px",
                                }}
                            >
                                Юридическая информация
                            </Typography>
                            <CustomTextField
                                placeholder="Данные наших документов"
                                text={quiz.config.info.law}
                                onChange={e => updateQuiz(quiz.id, quiz => {
                                    quiz.config.info.law = e.target.value;
                                })}
                            />
                            <Extra />
                        </>
                    )}
                </Box>
            </Box>
            {isSmallMonitor && (
                <Box sx={{ maxWidth: "1160px", marginBottom: "60px" }}>
                    {formState === "content" && (
                        <Button
                            onClick={() => setFormState("design")}
                            sx={{
                                display: "block",
                                marginTop: "20px",
                                padding: "0",
                                fontWeight: "bold",
                                fontSize: "16px",
                                color: "#7E2AEA",
                                textDecoration: "underline",
                                textUnderlineOffset: "2px",
                            }}
                        >
                            🡰 Вернуться к дизайну
                        </Button>
                    )}
                    {formState === "design" && (
                        <Button
                            onClick={() => setFormState("content")}
                            sx={{
                                display: "block",
                                marginLeft: "auto",
                                marginTop: "20px",
                                padding: "0",
                                fontWeight: "bold",
                                fontSize: "16px",
                                color: "#7E2AEA",
                                textDecoration: "underline",
                                textUnderlineOffset: "2px",
                            }}
                        >
                            Далее заполнить контент 🡲
                        </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",
            }}
        />
    );
}
