import {
    Box,
    Link,
    Typography,
    useMediaQuery,
    useTheme
} from "@mui/material";
import { setCropModal } from "@root/cropModal";
import { addQuestionVariant, uploadQuestionImage } from "@root/questions/actions";
import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
import { CropModal } from "@ui_kit/Modal/CropModal";
import { useState } from "react";
import { EnterIcon } from "../../../assets/icons/questionsPage/enterIcon";
import type { QuizQuestionImages } from "../../../model/questionTypes/images";
import { AnswerDraggableList } from "../AnswerDraggableList";
import ButtonsOptions from "../ButtonsOptions";
import { UploadImageModal } from "../UploadImage/UploadImageModal";
import SwitchAnswerOptionsPict from "./switchOptionsPict";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useDisclosure } from "../../../utils/useDisclosure";


interface Props {
    question: QuizQuestionImages;
}

export default function OptionsPicture({ question }: Props) {
    const theme = useTheme();
    const quizQid = useCurrentQuiz()?.qid;
    const [selectedVariantId, setSelectedVariantId] = useState<string | null>(null);
    const [switchState, setSwitchState] = useState("setting");
    const isMobile = useMediaQuery(theme.breakpoints.down(790));
    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={{ padding: "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={{ display: "flex", alignItems: "center", gap: "10px" }}>
                    <Link
                        component="button"
                        variant="body2"
                        sx={{ color: theme.palette.brightPurple.main }}
                        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>
            <ButtonsOptions switchState={switchState} SSHC={SSHC} question={question} />
            <SwitchAnswerOptionsPict switchState={switchState} question={question} />
        </>

    );
}
