import {
    Box,
    Link,
    Typography,
    useMediaQuery,
    useTheme
} from "@mui/material";
import { openCropModal } from "@root/cropModal";
import { setVariantImageUrl, setVariantOriginalImageUrl, updateQuestionsList } from "@root/questions";
import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
import { CropModal } from "@ui_kit/Modal/CropModal";
import { useState } from "react";
import { useParams } from "react-router-dom";
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";


interface Props {
    question: QuizQuestionImages;
}

export default function OptionsPicture({ question }: Props) {
    const [isUploadImageModalOpen, setIsUploadImageModalOpen] = useState(false);
    const [currentIndex, setCurrentIndex] = useState<number>(0);
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down(790));
    const quizId = Number(useParams().quizId);
    const [switchState, setSwitchState] = useState("setting");

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

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

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

        setVariantImageUrl(quizId, totalIndex, currentIndex, url);
        setVariantOriginalImageUrl(quizId, totalIndex, currentIndex, url);
        setIsUploadImageModalOpen(false);
        openCropModal(url, url);
    };

    const addNewAnswer = () => {
        const answerNew = question.content.variants.slice();
        answerNew.push({ answer: "", hints: "", extendedText: "", originalImageUrl: "" });

        updateQuestionsList<QuizQuestionImages>(quizId, totalIndex, {
            content: { ...question.content, variants: answerNew },
        });
    };

    function handleCropModalSaveClick(url: string) {
        setVariantImageUrl(quizId, totalIndex, currentIndex, url);
    }

    return (
        <>
            <Box sx={{ padding: "20px" }}>
                <AnswerDraggableList
                    variants={question.content.variants}
                    question={totalIndex}
                    additionalContent={(variant, index) => (
                        <>
                            {!isMobile && (
                                <AddOrEditImageButton
                                    imageSrc={variant.extendedText}
                                    onImageClick={() => {
                                        if (!("originalImageUrl" in variant)) return;

                                        setCurrentIndex(index);
                                        if (variant.extendedText) {
                                            return openCropModal(
                                                variant.extendedText,
                                                variant.originalImageUrl
                                            );
                                        }

                                        setIsUploadImageModalOpen(true);
                                    }}
                                    onPlusClick={() => {
                                        setCurrentIndex(index);
                                        setIsUploadImageModalOpen(true);
                                    }}
                                    sx={{ mx: "10px" }}
                                />
                            )}
                        </>
                    )}
                    additionalMobile={(variant, index) => (
                        <>
                            {isMobile && (
                                <AddOrEditImageButton
                                    imageSrc={variant.extendedText}
                                    onImageClick={() => {
                                        if (!("originalImageUrl" in variant)) return;

                                        setCurrentIndex(index);
                                        if (variant.extendedText) {
                                            return openCropModal(
                                                variant.extendedText,
                                                variant.originalImageUrl
                                            );
                                        }

                                        setIsUploadImageModalOpen(true);
                                    }}
                                    onPlusClick={() => {
                                        setCurrentIndex(index);
                                        setIsUploadImageModalOpen(true);
                                    }}
                                    sx={{ m: "8px", width: "auto" }}
                                />
                            )}
                        </>
                    )}
                />
                <UploadImageModal
                    open={isUploadImageModalOpen}
                    onClose={() => setIsUploadImageModalOpen(false)}
                    imgHC={handleImageUpload}
                />
                <CropModal onSaveImageClick={handleCropModalSaveClick} />
                <Box sx={{ display: "flex", alignItems: "center", gap: "10px" }}>
                    <Link
                        component="button"
                        variant="body2"
                        sx={{ color: theme.palette.brightPurple.main }}
                        onClick={addNewAnswer}
                    >
                        Добавьте ответ
                    </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} totalIndex={totalIndex} />
            <SwitchAnswerOptionsPict switchState={switchState} totalIndex={totalIndex} />
        </>

    );
}
