import { useState, useEffect, useCallback } from "react";
import axios from "axios";
import Cookies from "js-cookie";

const useSites = () => {
    const savedLayout = Cookies.get('sites-itemPerPage');
    const defaultLayout = savedLayout ? Number(savedLayout) : 5;
    
    const [sites, setSites] = useState([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [itemPerPage, setItemPerPage] = useState(defaultLayout);
    const [total, setTotal] = useState(0);
    const [search, setSearch] = useState("");

    const loadSites = useCallback(() => {
        axios.get('/api/sites/get_all', {
            params: { currentPage, itemPerPage, search }
        }).then((response) => {
            setSites(response.data.sites);
            setTotal(response.data.total);
        });
    }, [currentPage, itemPerPage, search]);

    useEffect(() => {
        loadSites();
    }, [loadSites]);


    useEffect(() => {
        Cookies.set('sites-itemPerPage', itemPerPage.toString());
    }, [itemPerPage]);

    const handlePageChange = (page: number) => setCurrentPage(page);

    return {
        sites,
        currentPage,
        itemPerPage,
        total,
        search,
        setSearch,
        handlePageChange,
        setItemPerPage,
        loadSites
    };
};

export default useSites;