import { useState, useEffect } from 'react';
import progressService from '../services/serviceProgress';

const useProgressClass = (classId) => {
    const [progress, setProgress] = useState([]);
    const [nameClass, setNameClass] = useState('class');

    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    const [search, setSearch] = useState("");
    const [sort, setSort] = useState("");
    const [page, setCurrentPage] = useState(1);
    const [limit, setLimit] = useState(20);
    const [totalPages, setTotalPages] = useState(0);
    const [totalData, setTotalData] = useState(null);
    
    const fetchData = async () => {
        setLoading(true);
        const dataId = {
            ID_CLASS: classId
        };

        try {
            const data = await progressService.fetchDataClassProgress(classId, search, sort, page, limit);
            console.log(data);
            setProgress(data.payload.studentActivities);
            setTotalPages(data.payload.totalPages);
            setTotalData(data.payload.totalItems);
            setNameClass(data.payload.studentActivities[0].NAME_CLASS);
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    };

    const handleSearchChange = () => {
        fetchData();
        setCurrentPage(1);
    }

    const handlePageChange = (pages) => {
        setCurrentPage(pages);
    }

    const handleLimitsChange = (e) => {
        setLimit(e.target.value);
        setCurrentPage(1);
    }

    useEffect(() => {
        fetchData();
    }, [page, limit, classId]);

    function formatLocalDate(isoDate) {
        const date = new Date(isoDate);
    
        const options = {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false,
            timeZone: 'Asia/Jakarta'
        };
        
        return new Intl.DateTimeFormat('id-ID', options).format(date)
            .replace(/\//g, '-')
            .replace(/\./g, ':') + ' WIB';
    }

    return { 
        progress,
        nameClass,
        loading, 
        error, 

        totalPages,
        totalData,
        setSearch,
        page, 
        handlePageChange,
        handleLimitsChange,
        handleSearchChange,
        formatLocalDate
    };
};

export default useProgressClass;
