import React, { useEffect, useState } from "react";
import styles from './Revise.module.scss';

import { Question } from "./question/Question";
import { Summary } from "./summary/Summary";
import { recollectionQuestions, updateRecollectionQuestion } from "../../services/recollectionquestions";
import { MobileShelf } from "../../shared/models/shelf";
import { MobileUser } from "../../shared/models/user";

export const Revise: React.FC = () => {
    const [progressState, setProgressState] = useState<'INTRO' | 'QUESTION' | 'END'>('QUESTION');
    const [questions, setQuestions] = useState<Array<any>>([]);
    const [answeredQuestions, setAnsweredQuestion] = useState<Array<{
        wordId: string,
        hasRecalled: boolean
    }>>([]);

    const [currentQuestion, setCurrentQuestion] = useState<number>(0);

    useEffect(() => {
        recollectionQuestions().then((response: any) => {
            let questions: Array<any> = response.data;
            const curatedQuestions: Array<any> = [];
            let allShelves: Array<MobileShelf> = [];
            
            const userProfile: MobileUser = JSON.parse(localStorage.getItem('userProfile') || "");
            
            userProfile.categories.forEach(category => {
                category.shelves?.forEach((shelf) => {
                    allShelves.push(shelf);
                });
            });

            questions.forEach((question) => {
                let index = allShelves.findIndex(shelf => shelf._id === question.shelfId);

                if (index !== undefined) {
                    const word = allShelves[index].words?.find(word => word.word._id === question.word)?.word;

                    if (word !== undefined) {
                        curatedQuestions.push({
                            ...question,
                            word: word
                        })
                    }

                }

            });

            setQuestions(curatedQuestions);

            if (curatedQuestions.length === 0) {
                setProgressState('END');
            }

        }, (e) => {
            window.alert("Failed to get questions");
            console.log(e);
        });
    }, []);



    return <section className={styles.revisePage}>
        { progressState === 'QUESTION' && <div>
            
            { questions.map((question, index) => {
                return currentQuestion === index && <Question key={index} totalQuestions={questions.length} questionNumber={currentQuestion} 
                word={question.word}
                selectOption={(flag) => {
                    let temp = answeredQuestions;

                    temp.push({
                        wordId: question.word._id,
                        hasRecalled: flag,
                    });

                    setAnsweredQuestion(temp);

                    console.log(question)

                    setTimeout(() => {

                        if (currentQuestion < questions.length - 1) {
                            setCurrentQuestion(currentQuestion + 1);
                        } else {
                            setProgressState('END');
                        }

                        updateRecollectionQuestion(question.shelfId, question.word._id, flag);

                    }, 200);

                }} />
            }) }

            <button className={styles.finishButton} onClick={() => setProgressState('END')}>
                Done
            </button>
        </div> }


        { progressState === 'END' && <div>
            <Summary />

            <button className={styles.finishButton} onClick={() => window.history.back()}>
                Done
            </button>
        </div> }
    </section>
}