import { useState, useEffect } from 'react';
import levelService from '../services/serviceMaterials';

const useMaterials = () => {
    const [levels, setLevels] = useState([]);
    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(7);
    const [totalPages, setTotalPages] = useState(0);
    const [totalData, setTotalData] = useState(null);
    
    const fetchData = async () => {
        setLoading(true);
        try {
            const data = await levelService.fetchData(search, sort, page, limit);
            setTotalPages(data.payload.totalPages);
            setTotalData(data.payload.totalItems);
            setLevels(data.payload.levels);
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    };

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

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

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

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

    return { 
        levels,
        loading, 
        error, 
        page, 
        totalData,
        totalPages,
        setSearch,
        handlePageChange,
        handleLimitsChange,
        handleSerachChange,
    };
};

export default useMaterials;
