import { useState, useEffect } from 'react';
import classService from '../services/serviceClasses';

const useClasses = () => {
    const [classes, setClasses] = useState([]);
    const [freeStudent, setStudentOption] = useState([]);
    const [studentSlug, setStudentSlug] = useState({});
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    
    const [assignStudents, setAssignStudents] = useState([]);
    const [assignClass, setAssignClass] = useState('');

    const [showAssign, setShowAssign] = useState(false);

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

    const assignStudentChange = (selectedOptions) => {
        setAssignStudents(selectedOptions);
    };
    const assignClassChange = (e) => {
        setAssignClass(e.target.value);
    };
    
    const handleShowAssign = () => setShowAssign(true);
    const handleClose = () => { 
        setShowAssign(false);
    };

    const handleCloseLoader = () => setShowLoader(false);
    const handleShowLoader = (title, description, loading = false, successMessage = '', confirmAction = false) => {
        setLoaderState({ title, description, loading, successMessage, confirmAction });
        setShowLoader(true);
    };

    const fetchData = async () => {
        setLoading(true);
        try {
            const data = await classService.fetchData("", "class", 1, 1000);
            setClasses(data.payload.classes);
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    };

    const fetchDataStudent = async () => {
        setLoading(true);
        try {
            const studentArray = {};
            const studentForOption = [];
            const dataStudent = await classService.fetchDataFreeStudent();
            dataStudent.payload.map((s, index) => {
                studentArray[s.NISN] = s.NAME_USERS;
                studentForOption[index] = {value: s.NISN, label: `${s.NISN} - ${s.NAME_USERS}`}
            });
            setStudentSlug(studentArray);
            setStudentOption(studentForOption);
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    };

    const assignStudentToClass = async () => {
        handleClose();
        handleShowLoader('Updated', '', true)

        const selectedStudent = assignStudents.map((selectedData) => ({
            NAME_USERS: studentSlug[selectedData.value],
            NISN: selectedData.value
        }));

        const assignData = {
            NAME_CLASS: assignClass,
            STUDENTS: selectedStudent
        };

        try {
            await classService.studentToClass(assignData);
        } catch (err) {
            setError(err);
        }finally{
            fetchDataStudent();
            fetchData();
            setLoaderState(prev => ({
                ...prev,
                loading: false,
                successMessage: 'Your data has been successfully updated.'
            }));
        }
    };

    useEffect(() => {
        fetchDataStudent();
        fetchData();
    }, []);


    return { 
        classes, 
        freeStudent,
        loading, 
        error, 
        showAssign,
        showLoader,
        loaderState,
        assignStudentToClass,
        assignStudentChange,
        assignClassChange,
        handleShowAssign,
        handleClose,
        handleCloseLoader,
    };
};

export default useClasses;
