import { ImageAddIcons } from "@icons/ImageAddIcons";
import { MessageIcon } from "@icons/messagIcon";
import { PointsIcon } from "@icons/questionsPage/PointsIcon";
import { DeleteIcon } from "@icons/questionsPage/deleteIcon";
import {
    Box,
    IconButton,
    InputAdornment,
    Link,
    Popover,
    TextField,
    TextareaAutosize,
    Typography,
    useMediaQuery,
    useTheme
} from "@mui/material";
import { setCropModal } from "@root/cropModal";
import { addQuestionVariant, uploadQuestionImage } from "@root/questions/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
import { CropModal } from "@ui_kit/Modal/CropModal";
import { useState } from "react";
import { useDisclosure } from "../../../utils/useDisclosure";
import { EnterIcon } from "../../../assets/icons/questionsPage/enterIcon";
import type { QuizQuestionVarImg } from "../../../model/questionTypes/varimg";
import { AnswerDraggableList } from "../AnswerDraggableList";
import ButtonsOptionsAndPict from "../ButtonsOptionsAndPict";
import { UploadImageModal } from "../UploadImage/UploadImageModal";
import SwitchOptionsAndPict from "./switchOptionsAndPict";


interface Props {
    question: QuizQuestionVarImg;
}

export default function OptionsAndPicture({ question }: Props) {
    const [switchState, setSwitchState] = useState("setting");
    const [selectedVariantId, setSelectedVariantId] = useState<string | null>(null);
    const theme = useTheme();
    const isTablet = useMediaQuery(theme.breakpoints.down(1000));
    const isMobile = useMediaQuery(theme.breakpoints.down(790));
    const quizQid = useCurrentQuiz()?.qid;
    const [isCropModalOpen, openCropModal, closeCropModal] = useDisclosure();
    const [isImageUploadOpen, openImageUploadModal, closeImageUploadModal] = useDisclosure();

    const SSHC = (data: string) => {
        setSwitchState(data);
    };

    const handleImageUpload = async (files: FileList | null) => {
        if (!files?.length || !selectedVariantId) return;

        const [file] = Array.from(files);

        const url = await uploadQuestionImage(question.id, quizQid, file, (question, url) => {
            if (!("variants" in question.content)) return;

            const variant = question.content.variants.find(variant => variant.id === selectedVariantId);
            if (!variant) return;

            variant.extendedText = url;
            variant.originalImageUrl = url;
        });
        closeImageUploadModal();
        setCropModal(file, url);
        openCropModal();
    };

    function handleCropModalSaveClick(imageBlob: Blob) {
        if (!selectedVariantId) return;

        uploadQuestionImage(question.id, quizQid, imageBlob, (question, url) => {
            if (!("variants" in question.content)) return;

            const variant = question.content.variants.find(variant => variant.id === selectedVariantId);
            if (!variant) return;

            variant.extendedText = url;
        });
    }

    return (
        <>
            <Box sx={{ pl: "20px", pr: "20px" }}>
                <AnswerDraggableList
                    question={question}
                    additionalContent={(variant) => (
                        <>
                            {!isMobile && (
                                <AddOrEditImageButton
                                    imageSrc={variant.extendedText}
                                    onImageClick={() => {
                                        setSelectedVariantId(variant.id);
                                        if (variant.extendedText) {
                                            openCropModal();
                                            setCropModal(
                                                variant.extendedText,
                                                variant.originalImageUrl
                                            );

                                            return;
                                        }

                                        openImageUploadModal();
                                    }}
                                    onPlusClick={() => {
                                        setSelectedVariantId(variant.id);
                                        openImageUploadModal();
                                    }}
                                    sx={{ mx: "10px" }}
                                />
                            )}
                        </>
                    )}
                    additionalMobile={(variant) => (
                        <>
                            {isMobile && (
                                <AddOrEditImageButton
                                    imageSrc={variant.extendedText}
                                    onImageClick={() => {
                                        setSelectedVariantId(variant.id);
                                        if (variant.extendedText) {
                                            openCropModal();
                                            setCropModal(
                                                variant.extendedText,
                                                variant.originalImageUrl
                                            );

                                            return;
                                        }

                                        openImageUploadModal();
                                    }}
                                    onPlusClick={() => {
                                        setSelectedVariantId(variant.id);
                                        openImageUploadModal();
                                    }}
                                    sx={{ m: "8px", width: "auto" }}
                                />
                            )}
                        </>
                    )}
                />
                <UploadImageModal isOpen={isImageUploadOpen} onClose={closeImageUploadModal} imgHC={handleImageUpload} />
                <CropModal isOpen={isCropModalOpen} onClose={closeCropModal} onSaveImageClick={handleCropModalSaveClick} />
                <Box
                    sx={{
                        width: "100%",
                        border: "1px solid #9A9AAF",
                        borderRadius: "8px",
                        display: isTablet ? "block" : "none",
                    }}
                >
                    <TextField
                        fullWidth
                        focused={false}
                        placeholder={"Добавьте ответ"}
                        multiline={question.content.largeCheck}
                        InputProps={{
                            startAdornment: (
                                <>
                                    <InputAdornment position="start">
                                        <PointsIcon
                                            style={{ color: "#9A9AAF", fontSize: "30px" }}
                                        />
                                    </InputAdornment>
                                    {!isMobile && (
                                        <Box
                                            sx={{
                                                width: "60px",
                                                height: "40px",
                                                background: "#EEE4FC",
                                                display: "flex",
                                                justifyContent: "space-between",
                                                marginRight: "20px",
                                                marginLeft: "12px",
                                            }}
                                        >
                                            <Box
                                                sx={{
                                                    display: "flex",
                                                    alignItems: "center",
                                                    justifyContent: "center",
                                                    width: "100%",
                                                }}
                                            >
                                                <ImageAddIcons fontSize="22px" color="#7E2AEA" />
                                            </Box>
                                            <span
                                                style={{
                                                    display: "flex",
                                                    alignItems: "center",
                                                    justifyContent: "center",
                                                    background: "#7E2AEA",
                                                    height: "100%",
                                                    width: "25px",
                                                    color: "white",
                                                    fontSize: "15px",
                                                }}
                                            >
                                                +
                                            </span>
                                        </Box>
                                    )}
                                </>
                            ),
                            endAdornment: (
                                <InputAdornment position="end">
                                    <IconButton
                                        sx={{ padding: "0" }}
                                        aria-describedby="my-popover-id"
                                    >
                                        <MessageIcon
                                            style={{
                                                color: "#9A9AAF",
                                                fontSize: "30px",
                                                marginRight: "6.5px",
                                            }}
                                        />
                                    </IconButton>
                                    <Popover
                                        id="my-popover-id"
                                        anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
                                        open={false}
                                    >
                                        <TextareaAutosize
                                            style={{ margin: "10px" }}
                                            placeholder="Подсказка для этого ответа"
                                        />
                                    </Popover>
                                    <IconButton sx={{ padding: "0" }}>
                                        <DeleteIcon
                                            style={{
                                                color: theme.palette.grey2.main,
                                                marginRight: "-1px",
                                            }}
                                        />
                                    </IconButton>
                                </InputAdornment>
                            ),
                        }}
                        sx={{
                            "& .MuiInputBase-root": {
                                padding: "13.5px",
                                borderRadius: "10px",
                                background: "#ffffff",
                                height: "48px",
                            },
                            "& .MuiOutlinedInput-notchedOutline": {
                                border: "none",
                            },
                        }}
                        inputProps={{
                            sx: { fontSize: "18px", lineHeight: "21px", py: 0 },
                        }}
                    />

                    {isMobile && (
                        <Box
                            sx={{
                                display: "flex",
                                alignItems: "center",
                                m: "8px",
                                position: "relative",
                            }}
                        >
                            <Box
                                sx={{ width: "100%", background: "#EEE4FC", height: "40px" }}
                            />
                            <ImageAddIcons
                                style={{
                                    position: "absolute",
                                    color: "#7E2AEA",
                                    fontSize: "20px",
                                    left: "45%",
                                    right: "55%",
                                }}
                            />
                            <Box
                                sx={{
                                    display: "flex",
                                    justifyContent: "center",
                                    alignItems: "center",
                                    width: "20px",
                                    background: "#EEE4FC",
                                    height: "40px",
                                    color: "white",
                                    backgroundColor: "#7E2AEA",
                                }}
                            >
                                <Box
                                    sx={{ width: "100%", background: "#EEE4FC", height: "40px" }}
                                />
                                <ImageAddIcons
                                    style={{
                                        position: "absolute",
                                        color: "#7E2AEA",
                                        fontSize: "20px",
                                        left: "45%",
                                        right: "55%",
                                    }}
                                />
                                <Box
                                    sx={{
                                        display: "flex",
                                        justifyContent: "center",
                                        alignItems: "center",
                                        width: "20px",
                                        background: "#EEE4FC",
                                        height: "40px",
                                        color: "white",
                                        backgroundColor: "#7E2AEA",
                                    }}
                                >
                                    +
                                </Box>
                            </Box>
                        </Box>
                    )}
                </Box>
                <Box
                    sx={{
                        display: "flex",
                        alignItems: "center",
                        marginBottom: "17px",
                    }}
                >
                    <Link
                        component="button"
                        variant="body2"
                        sx={{
                            color: theme.palette.brightPurple.main,
                            fontWeight: "400",
                            fontSize: "16px",
                            mr: "4px",
                            height: "19px",
                        }}
                        onClick={() => {
                            addQuestionVariant(question.id);
                        }}
                    >
                        Добавьте ответ
                    </Link>
                    {isMobile ? null : (
                        <>
                            <Typography
                                sx={{
                                    fontWeight: 400,
                                    lineHeight: "21.33px",
                                    color: theme.palette.grey2.main,
                                    fontSize: "16px",
                                }}
                            >
                                или нажмите Enter
                            </Typography>
                            <EnterIcon
                                style={{
                                    color: "#7E2AEA",
                                    fontSize: "24px",
                                    marginLeft: "6px",
                                }}
                            />
                        </>
                    )}
                </Box>
            </Box>
            <ButtonsOptionsAndPict
                switchState={switchState}
                SSHC={SSHC}
                question={question}
            />
            <SwitchOptionsAndPict switchState={switchState} question={question} />
        </>

    );
}
