import {
    Box,
    Link,
    Typography,
    useMediaQuery,
    useTheme
} from "@mui/material";
import { useState } from "react";
import { useParams } from "react-router-dom";

import { questionStore, updateQuestionsList } from "@root/questions";
import { CropModal } from "@ui_kit/Modal/CropModal";
import { AnswerDraggableList } from "../AnswerDraggableList";
import ButtonsOptions from "../ButtonsOptions";
import { UploadImageModal } from "../UploadImage/UploadImageModal";

import { EnterIcon } from "../../../assets/icons/questionsPage/enterIcon";
import SwitchAnswerOptionsPict from "./switchOptionsPict";

import AddOrEditImageButton from "@ui_kit/AddOrEditImageButton";
import { produce } from "immer";
import type { QuizQuestionImages } from "../../../model/questionTypes/images";

interface Props {
    totalIndex: number;
}

export default function OptionsPicture({ totalIndex }: Props) {
    const [isUploadImageModalOpen, setIsUploadImageModalOpen] = useState(false);
    const [isCropModalOpen, setIsCropModalOpen] = useState<boolean>(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 { listQuestions } = questionStore();
    const question = listQuestions[quizId][totalIndex] as QuizQuestionImages;

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

    const uploadImage = (files: FileList | null) => {
        if (files?.length) {
            const [file] = Array.from(files);

            const clonedContent = { ...question.content };
            clonedContent.variants[currentIndex].extendedText =
                URL.createObjectURL(file);
            updateQuestionsList<QuizQuestionImages>(quizId, totalIndex, {
                content: clonedContent,
            });

            setIsUploadImageModalOpen(false);
            setIsCropModalOpen(true);
        }
    };

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

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

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

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

                                        setIsUploadImageModalOpen(true);
                                    }}
                                    onPlusClick={() => {
                                        setCurrentIndex(index);
                                        setIsUploadImageModalOpen(true);
                                    }}
                                    sx={{ m: "8px", width: "auto" }}
                                />
                            )}
                        </>
                    )}
                />
                <UploadImageModal
                    open={isUploadImageModalOpen}
                    onClose={() => setIsUploadImageModalOpen(false)}
                    imgHC={uploadImage}
                />
                <CropModal
                    opened={isCropModalOpen}
                    onClose={() => setIsCropModalOpen(false)}
                    picture={question.content.variants[currentIndex]?.extendedText}
                    onCropPress={url => {
                        const content = produce(question.content, draft => {
                            draft.variants[currentIndex].extendedText = url;
                        });
                        updateQuestionsList<QuizQuestionImages>(quizId, totalIndex, {
                            content,
                        });
                    }}
                />
                <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} />
        </>
    );
}
