import { useState, useEffect, useRef } from 'react';
import exerciseService from '../services/serviceExercises';
import { MEDIA_URL } from '../../../../utils/Constant';

function videoUrlChecker(url) {
    const youtubeRegex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
    const googleDriveRegex = /https?:\/\/drive\.google\.com\/file\/d\/([a-zA-Z0-9_-]+)\/(?:view|preview)/;
    
    if (youtubeRegex.test(url)) {
      return 'Youtube';
    } else if (googleDriveRegex.test(url)) {
      return 'Gdrive';
    } else {
      return 'none';
    }
}

const useUpdateExercises = (levelId) => {
    const [exerciseData, setExerciseData] = useState([]);
    const [isUpdated, setIsUpdated] = useState([]);
    const [levelName, setLevelName] = useState('Level');
    const [sectionName, setSectionName] = useState('section');
    const [topicName, setTopicName] = useState('topic');
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const mediaPath = `${MEDIA_URL}/exercise`;

    const [formData, setFormData] = useState({
        ID_ADMIN_EXERCISE: "",
        ID_LEVEL: "",
        TITLE: "",
        QUESTION: "",
        QUESTION_TYPE: "",
        SCORE_WEIGHT: "",
        AUDIO: "",
        IMAGE: "",
        VIDEO: "",
        multipleChoices: "",
        trueFalse: "",
        matchingPairs: {},
    });
    
    const [imageContainer, setImageContainer] = useState("");
    const [audioContainer, setAudioContainer] = useState("");

    const [selectedQuestion, setSelectedQuestion] = useState(false);

    const [show, setShow] = useState(false);
    const [showLoader, setShowLoader] = useState(false);
    const [loaderState, setLoaderState] = useState({ loading: false, successMessage: '', title: '', description: '', confirmAction: false });

    const resetForm = () =>{
        setSelectedQuestion(false);
        setFormData({
            ID_ADMIN_EXERCISE:"",
            ID_LEVEL:"",
            TITLE:"",
            QUESTION:"",
            QUESTION_TYPE:"",
            SCORE_WEIGHT:"",
            AUDIO:'',
            IMAGE:'',
            VIDEO:'',
            multipleChoices:"",
            trueFalse:"",
            matchingPairs:{},
        });
    }
    
    const handleCloseLoader = () => setShowLoader(false);
    const handleShowLoader = (title, description, loading = false, successMessage = '', confirmAction = false) => {
        setLoaderState({ title, description, loading, successMessage, confirmAction });
        setShowLoader(true);
    };

    const [mediaPreview, setMediaPreview] = useState(null);
    const handleFormChangeMedia = (e) => {
        const file = e.target.files[0]; 
        if (file) {
            const mediaUrl = URL.createObjectURL(file); 
            setMediaPreview(mediaUrl); 
        }
        setFormData({ ...formData, [e.target.name]: file });
    };
    
    const [selectedQuestionNumber, setSelectedQuestionNumber] = useState(null);
    const handleShow = (data) => {
        setImageContainer("");
        setAudioContainer("");
        setSelectedQuestion(true);
        setSelectedQuestionNumber(data+1);
        setFormData({
            ID_ADMIN_EXERCISE: exerciseData[data].ID_ADMIN_EXERCISE || "",
            ID_LEVEL: exerciseData[data].ID_LEVEL || "",
            TITLE: exerciseData[data].TITLE || "",
            QUESTION: exerciseData[data].QUESTION || "",
            QUESTION_TYPE: exerciseData[data].QUESTION_TYPE || "",
            SCORE_WEIGHT: exerciseData[data].SCORE_WEIGHT || "",
            AUDIO: exerciseData[data].AUDIO || '',
            IMAGE: exerciseData[data].IMAGE || '',
            VIDEO: exerciseData[data].VIDEO || '',
            multipleChoices: exerciseData[data].multipleChoices || "",
            trueFalse: exerciseData[data].trueFalse || "",
            matchingPairs: exerciseData[data].matchingPairs || {},
        });
        if(exerciseData[data].IMAGE){
            setImageContainer(exerciseData[data].IMAGE);
        }
        if(exerciseData[data].AUDIO){
            setAudioContainer(exerciseData[data].AUDIO);
        }
        setShow(true);
    };
    const handleClose = () => {
        setShow(false); 
        resetForm(); 
        setSelectedQuestion(null);
        setMediaPreview(null);

        setImageContainer("");
        setAudioContainer("");
    };

    const handleShowNewData = () => {
        setSelectedQuestionNumber(null);
        resetForm();
        setShow(true);
    }
    
    const [validUrl, setValidUrl] = useState('');
    const [urlInput, setUrlInput] = useState(null);
    const [showUrlModal, setShowUrlModal] = useState(false);
    const handleShowUrlModal = () => {setShowUrlModal(true); setValidUrl('')};
    const handleCloseUrlModal = () => {setShowUrlModal(false); setValidUrl('')};
    const handleUrlInput = (e) => {
        setUrlInput(e.target.value)
    };
    const handleCheckUrl = () => {
        const check = videoUrlChecker(urlInput);
        if (check === "Gdrive" || check === "Youtube") {
            setValidUrl('valid');
        }else{
            setValidUrl('invalid');
        }
    };
    const handleSetVideoUrl = () => {
        setFormData({...formData, VIDEO: urlInput});
        handleCloseUrlModal();
    };
    
    const handleFormChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleFormChangeAnswer = (e) => {
        if (formData.QUESTION_TYPE === "TFQ") {
            setFormData({...formData, trueFalse: e.target.value});
        }else if (formData.QUESTION_TYPE === "MCQ") {
            setFormData({
                ...formData, 
                multipleChoices: {
                    ...formData.multipleChoices, 
                    [0]: {
                        ...formData.multipleChoices[0],
                        [e.target.name]: e.target.value
                    },
                }
            });
        }else if (formData.QUESTION_TYPE === "MPQ") {
            const match = e.target.name.match(/^(\d+)_(.*)/);
            const index = match[1];
            const side = match[2];
            setFormData({
                ...formData,
                matchingPairs: {
                  ...formData.matchingPairs,
                  [index]: {
                    ...formData.matchingPairs[index],
                    [side]: e.target.value,
                  },
                },
            });
        }
    };

    const handleFormResetMedia = () => {
        setFormData({...formData, AUDIO: "", IMAGE: "", VIDEO: ""});
    }

    const createQuestion = async () => {
        const createData = new FormData();
        createData.append('exercises[0][ID_LEVEL]', levelId);
        createData.append('exercises[0][QUESTION]', formData.QUESTION);
        createData.append('exercises[0][SCORE_WEIGHT]', formData.SCORE_WEIGHT);
        createData.append('exercises[0][QUESTION_TYPE]', formData.QUESTION_TYPE);
        if (formData.VIDEO) {
            createData.append('exercises[0][VIDEO]', formData.VIDEO);
        }else if (formData.IMAGE) {
            createData.append('IMAGE[0]', formData.IMAGE);
        }else if (formData.AUDIO) {
            createData.append('AUDIO[0]', formData.AUDIO);
        }
        
        if (formData.QUESTION_TYPE === "TFQ") {
            createData.append('exercises[0][IS_TRUE]', formData.trueFalse);
        }else if (formData.QUESTION_TYPE === "MCQ") {
            createData.append('exercises[0][OPTION_A]', formData.multipleChoices[0].OPTION_A);
            createData.append('exercises[0][OPTION_B]', formData.multipleChoices[0].OPTION_B);
            createData.append('exercises[0][OPTION_C]', formData.multipleChoices[0].OPTION_C);
            createData.append('exercises[0][OPTION_D]', formData.multipleChoices[0].OPTION_D);
            if (formData.multipleChoices[0].OPTION_E) {
                createData.append('exercises[0][OPTION_E]', formData.multipleChoices[0].OPTION_E);
            }
            createData.append('exercises[0][ANSWER_KEY]', formData.multipleChoices[0].ANSWER_KEY);
        }else if (formData.QUESTION_TYPE === "MPQ") {
            Object.keys(formData.matchingPairs).forEach((key, newIndex) => {
                createData.append(`exercises[0][PAIRS][${newIndex}][LEFT_PAIR]`, formData.matchingPairs[key].LEFT_PAIR);
                createData.append(`exercises[0][PAIRS][${newIndex}][RIGHT_PAIR]`, formData.matchingPairs[key].RIGHT_PAIR);
            });
        }

        handleShowLoader('Created', '', true);
        try {
            const create = await exerciseService.createData(createData);
            setExerciseData((prevQuestion) => [...prevQuestion, create.payload]);
            handleClose();
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Question successfully created.'
            }));
        } catch (err) {
            setLoaderState(prev => ({
                ...prev,
                title: "ERROR",
                loading: false,
                successMessage: err.response.data.message
            }));
        }
    };

    const updateQuestion = async () => {
        const id = formData.ID_ADMIN_EXERCISE;

        const updateData = new FormData();
        updateData.append('ID_LEVEL', levelId);
        updateData.append('QUESTION', formData.QUESTION);
        updateData.append('SCORE_WEIGHT', formData.SCORE_WEIGHT);
        if (formData.VIDEO) {
            updateData.append('VIDEO', formData.VIDEO);
        }else if (formData.IMAGE) {
            updateData.append('IMAGE', formData.IMAGE);
        }else if (formData.AUDIO) {
            updateData.append('AUDIO', formData.AUDIO);
        }

        if (formData.VIDEO === '') {
            updateData.append('VIDEO', "");
        }
        if (formData.IMAGE === '') {
            updateData.append('IMAGE', "");
        }
        if (formData.AUDIO === '') {
            updateData.append('AUDIO', "");
        }
        
        if (formData.QUESTION_TYPE === "TFQ") {
            if (typeof formData.trueFalse === 'object') {
                updateData.append('IS_TRUE', formData.trueFalse[0].IS_TRUE);
            } else {
                updateData.append('IS_TRUE', formData.trueFalse);
            }
        }else if (formData.QUESTION_TYPE === "MCQ") {
            updateData.append('OPTION_A', formData.multipleChoices[0].OPTION_A);
            updateData.append('OPTION_B', formData.multipleChoices[0].OPTION_B);
            updateData.append('OPTION_C', formData.multipleChoices[0].OPTION_C);
            updateData.append('OPTION_D', formData.multipleChoices[0].OPTION_D);
            if (formData.multipleChoices[0].OPTION_E) {
                updateData.append('OPTION_E', formData.multipleChoices[0].OPTION_E);
            }
            updateData.append('ANSWER_KEY', formData.multipleChoices[0].ANSWER_KEY);
        }else if (formData.QUESTION_TYPE === "MPQ") {
            Object.keys(formData.matchingPairs).forEach((key, newIndex) => {
                updateData.append(`PAIRS[${newIndex}][LEFT_PAIR]`, formData.matchingPairs[key].LEFT_PAIR);
                updateData.append(`PAIRS[${newIndex}][RIGHT_PAIR]`, formData.matchingPairs[key].RIGHT_PAIR);
            });
        }

        //media checker delete
        if (imageContainer != '' && imageContainer != formData.IMAGE) {
            await exerciseService.deleteMedia(id, 'image');
            setImageContainer('');
            setAudioContainer('');
        }
        if (audioContainer != '' && audioContainer != formData.AUDIO) {
            await exerciseService.deleteMedia(id, 'audio');
            setImageContainer('');
            setAudioContainer('');
        }

        handleShowLoader('Updated', '', true);
        try {
            const update = await exerciseService.updateData(id, updateData);
            setExerciseData((prevQuestion) => 
                prevQuestion.map((s) => (s.ID_ADMIN_EXERCISE === id ? update.payload : s))
            );
            handleClose();
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Question successfully updated.'
            }));
        } catch (err) {
            setLoaderState(prev => ({
                ...prev,
                title: "ERROR",
                loading: false,
                successMessage: err.message
            }));
        }
    };

    const deleteQuestion = async (index) => {
        const id = exerciseData[index].ID_ADMIN_EXERCISE;
        handleShowLoader('Deleted', `Are you sure you want to delete Question ${index+1}?`, false, '', true);
        const confirmDelete = async () => {
            handleCloseLoader();

            handleShowLoader('Deleted', '', true)
            try {
                await exerciseService.deleteData(id);
                setExerciseData((prevSections) => prevSections.filter((s) => s.ID_ADMIN_EXERCISE !== id));
                setLoaderState(prev => ({
                    ...prev,
                    loading: false,
                    successMessage: `Question has been successfully deleted.`
                }));
            } catch (err) {
                setLoaderState(prev => ({
                    ...prev,
                    title: "ERROR",
                    loading: false,
                    successMessage: err.message
                }));
            }
        }
        setLoaderState(prev => ({ ...prev, handleConfirm: confirmDelete }));
    };

    

    const sortingQuestion = async () => {
        const id = levelId;
        const sortingData = {
            ID_LEVEL: levelId,
            exercises: exerciseData.map(item => ({
                ID_ADMIN_EXERCISE: item.ID_ADMIN_EXERCISE,
                TITLE: item.TITLE
            }))
        };

        handleShowLoader('Updated', '', true);
        try {
            await exerciseService.sortingData(sortingData);
            // console.log(sorting.payload);
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Exercise successfully updated.'
            }));
        } catch (err) {
            setLoaderState(prev => ({
                ...prev,
                title: "ERROR",
                loading: false,
                successMessage: err.message
            }));
        }
    };

    useEffect(() => {
        const fetchData = async () => {
            setLoading(true);
            try {
                const setUpdated = [];
                const data = await exerciseService.getExerciseByLevelId(levelId);
                // console.log(data.EXERCISES);
                setLevelName(data.NAME_LEVEL);
                setSectionName(data.NAME_SECTION);
                setTopicName(data.NAME_TOPIC);
                setExerciseData(data.EXERCISES);

                for (let i = 0; i < data.EXERCISES.length; i++) {
                    setUpdated[i] = false;
                    if (i === data.EXERCISES.length-1) {
                        setIsUpdated(setUpdated);
                    }
                }
            } catch (error) {
                setError(error);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [levelId]);

    return { 
        exerciseData, 
        setExerciseData,
        formData, 
        levelName,
        sectionName, 
        topicName, 
        loading, 
        error, 
        mediaPath, 
        mediaPreview,
        handleFormChange, 
        handleFormChangeAnswer,
        handleFormChangeMedia,
        handleFormResetMedia,
        showLoader,
        handleCloseLoader,
        loaderState,

        createQuestion,
        updateQuestion,
        deleteQuestion,
        sortingQuestion,

        selectedQuestion,
        selectedQuestionNumber,
        show,
        handleShow,
        handleClose,
        handleShowNewData,
        
        validUrl,
        handleCheckUrl,
        handleUrlInput,
        showUrlModal,
        handleShowUrlModal,
        handleCloseUrlModal,
        handleSetVideoUrl
    };
};

export default useUpdateExercises;