import { FC, useEffect, useState } from "react";
import { CropModal } from "./CropModal";
import {
    type ScreenStepsTypes,
    type CropOnOpenType,
    type EditedImages,
    type CropOnDeleteIamgeClick,
    type Writable,
    workSpaceTypesList,
    DEFAULTCROPRULES,
    EditedImage,
    WorkSpaceTypes,
} from "@/model/CropModal/CropModal"
import { isImageBlobAGifFile } from "@/utils/isImageBlobAGifFile";
import AlertModalDeleteImage from "./AlertModalDeleteImage"
import { getModifiedImageBlob } from "./utils/imageManipulation";
import { updateQuestion, uploadQuestionImage } from "@/stores/questions/actions";

export const CropModalInit: FC<CropOnOpenType> = ({
    open,
    originalImageUrl,
    imageBlob,
    editedUrlImagesList,
    questionId,
    questionType,
    quizId,
    variantId,

    selfClose,
    setPictureUploading,
}) => {

    const [acceptedOriginalImageUrl, setOriginalImageUrl] = useState("");
    const [editedImages, setEditedImages] = useState<Record<keyof WorkSpaceTypes, EditedImage> | null>(null);
    const [readyDelete, setReadyDelete] = useState(false);

    useEffect(() => {
        if (open) {
            //Если нам не дали с чем работать, то и работать не нужно
            if (Boolean(imageBlob) || Boolean(originalImageUrl)) {
                (async () => {
                    let newImageBlob = imageBlob;
                    if (originalImageUrl !== undefined) {
                        const response = await fetch(originalImageUrl);
                        newImageBlob = await response.blob();
                    };

                    if (newImageBlob) {
                        const isGif = await isImageBlobAGifFile(newImageBlob);
                        if (isGif) {
                            saveImagesAndRules(newImageBlob);
                            return setPictureUploading(false);
                        }
                        //Для работы нам нужны урлы. Оригинальной и редактированных картинок
                        let newOriginalImageUrl = originalImageUrl || URL.createObjectURL(newImageBlob)
                        if (questionId) {
                            if (questionType) {
                                const workSpaceTypesCONST = workSpaceTypesList[questionType];

                                type WritableWorkSpaceTypesCONST = Writable<typeof workSpaceTypesCONST>;
                                const writableEditedImagesList: WritableWorkSpaceTypesCONST = { ...workSpaceTypesList[questionType] }; // Теперь object не readonly

                                type Keys = keyof typeof writableEditedImagesList;
                                const newEditedImagesList = {} as Record<Keys, EditedImage>;


                                //Если вопрос умничка и знает что ему нужно
                                if (Boolean(editedUrlImagesList)) {


                                    for (let k in editedUrlImagesList) {
                                        let key = k as Keys;

                                        if (key in writableEditedImagesList) {
                                            newEditedImagesList[key] = {
                                                ...writableEditedImagesList[key],
                                                url: editedUrlImagesList[key] ?? originalImageUrl,
                                                newRules: DEFAULTCROPRULES
                                            } as EditedImage;
                                        }
                                    }
                                } else { // Если в первый раз, то создаём ему бланк
                                    for (let k in workSpaceTypesCONST) {
                                        let key = k as Keys;

                                        if (key in writableEditedImagesList) {
                                            newEditedImagesList[key] = {
                                                ...writableEditedImagesList[key],
                                                url: originalImageUrl,
                                                newRules: DEFAULTCROPRULES
                                            } as EditedImage;
                                        }
                                    }
                                }
                                setOriginalImageUrl(newOriginalImageUrl);
                                setEditedImages(newEditedImagesList);
                            } else {
                                throw new Error("Не передан тип вопроса")
                            }
                        } else {
                            throw new Error("Не передан id вопроса")
                        }
                    }
                })()
            }
        }

    }, [open, originalImageUrl, editedUrlImagesList, questionId, questionType])

    const closeModal = () => {
        setReadyDelete(false)
        setOriginalImageUrl("");
        setEditedImages(null);
        selfClose()

    }

    const handleCropModalDeleteImageClick = () => {
        if (variantId) {//Работаем с вариантом
            updateQuestion(questionId, (question) => {
                if ("variants" in question.content) {

                    const variant = question.content.variants.find(
                        (variant) => variant.id === variantId,
                    );
                    if (!variant) return console.error("В вопросе не был найден вариант ", variantId);

                    variant.extendedText = "";
                    variant.originalImageUrl = "";
                    if ("editedUrlImagesList" in variant) variant.editedUrlImagesList = null;

                }
            })
        } else {//Работаем с контентом
            updateQuestion(questionId, (question) => {
                question.content.back = null;
                question.content.originalBack = null;
                if ("editedUrlImagesList" in question.content) question.content.editedUrlImagesList = null;
            })
        }
        //сохранить пустую строку и дефолтные настройки картинки в самом вопросе, не информируя БД о удалении картинки
        closeModal()
    };

    const saveImagesAndRules = async () => {
        setPictureUploading(true)
        if (editedImages === null) return;
        
        closeModal();

        //массив запросов
        const requests: Promise<void>[] = [];

        //Преобразовываем и отправляем на бек картинки.

        if (variantId) {//Работаем с вариантом
            for (let k in editedImages) {
                requests.push(new Promise(async (resolve) => {

                    let key = k;

                    const img = document.createElement("img");
                    img.crossOrigin = 'anonymous';
                    img.src = editedImages[key].url;
                    const blob = await getModifiedImageBlob(img, editedImages[key].newRules.crop, editedImages[key].newRules.darken);

                    uploadQuestionImage(questionId, quizId, blob, (question, url) => {
                        if (!("variants" in question.content)) return;

                        const variant = question.content.variants.find(
                            (variant) => variant.id === variantId,
                        );
                        if (!variant) return;
                        if (!variant.editedUrlImagesList) variant.editedUrlImagesList = {}

                        variant.editedUrlImagesList[key] = url;
                        resolve()
                    });
                }))
            }
        } else {//Работаем с контентом

            for (let k in editedImages) {
                requests.push(new Promise(async (resolve) => {

                    let key = k;

                    const img = document.createElement("img");
                    img.crossOrigin = 'anonymous';
                    img.src = editedImages[key].url;
                    const blob = await getModifiedImageBlob(img, editedImages[key].newRules.crop, editedImages[key].newRules.darken);

                    uploadQuestionImage(questionId, quizId, blob, (question, url) => {
                        if (!question.content.editedUrlImagesList) question.content.editedUrlImagesList = {};

                        question.content.editedUrlImagesList[key] = url;
                        resolve()
                    });
                }))
            }
        }
        await Promise.all(requests)
        setPictureUploading(false);
    };

    if (acceptedOriginalImageUrl.length === 0) return <></>
    if (workSpaceTypesList[questionType] === undefined) return <></>
    if (editedImages === null) return <></>

    return (
        <>
            <CropModal
                open={open}
                editedImages={editedImages}
                workSpaceTypes={workSpaceTypesList[questionType]}
                originalImageUrl={acceptedOriginalImageUrl}

                setEditedImages={setEditedImages}
                onSaveImageClick={saveImagesAndRules}
                closeCropModal={closeModal}
                onDeleteClick={() => setReadyDelete(true)}
            />
            <AlertModalDeleteImage
                open={readyDelete}
                cancelDelete={() => setReadyDelete(false)}
                deleteImage={handleCropModalDeleteImageClick}
            />
        </>
    )

};


// function handleCropModalSaveClick(imageBlob: Blob) {         OptionsPicture
//     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;
//     });
//   }