import { useEffect, useState } from 'react';
import levelService from '../services/levelService';
import { useSlugContext } from '../../../../utils/SlugContext';

function extractLevelNumber(levelName) {
    if (!levelName) {
        return null;
    }
    const number = levelName.match(/\d+/);
    return number ? parseInt(number[0], 10) : 0;
}

const useLevels = (section, topic) => {
    const [levels, setLevels] = useState([]);
    const [lastCompletedLevel, setLastCompletedLevel] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const { topicSlugMap } = useSlugContext();

    const savedLevel = JSON.parse(localStorage.getItem('savedLevels'));
    const savedScore = JSON.parse(localStorage.getItem('savedScores'));

    const levelDesc = ['PRETEST: Introduction to Topic', 'Beginer', 'Advanced Concepts', 'Practice Exercises', 'Case Studies', 'Vacational Test', 'Final Test'];

    const lastLevel = [{
        ID_STUDENT_LEARNING : "6b81668b-42e2-4254-af44-74063ac61ece",
        ID_LEVEL : "0f89df44-edf8-40f6-a81b-1bc77628d798",
        NAME_LEVEL : "Level 4",
        FINISHED_AT : "2024-09-12T04:23:44.000Z"
    }];

    useEffect(() => {
        const fetchData = async () => {
            setLoading(true);
            try {
                const response = await levelService.fetchLevels(topicSlugMap[topic]);
                setLevels(response.data.levels);

                // const next = await levelService.fetchNextLearning(topicSlugMap[topic]);
                // const data = await levelService.fetchLevels(next);
                // if (data.length > 0) {
                //     setLevels(data.levels);
                //     setLastCompletedLevel(data.lastCompletedLevel);   
                // }else{
                //     const datas = await levelService.levelnol(topicSlugMap[topic]);
                //     setLevels(datas.levels);
                //     setLastCompletedLevel(datas.lastCompletedLevel);
                // }
                
            } catch (err) {
                setError(err);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [section, topic]);

    const isLevelUnlocked = (levelIndex) => {
        if (levelIndex !== 0) {
            console.log(levels[levelIndex]);
            if ("CONTENT" in levels[levelIndex]) {
                return true;
            }else{
                return false;
            }
        }else{
            return true;
        }

    };
    return { levels, lastCompletedLevel,  loading, error, isLevelUnlocked, levelDesc};
};

export default useLevels;