import { useState, useEffect, useCallback } from "react";
import axios from "axios";
import { Site } from "@/app/types";
import Cookies from "js-cookie";

const useSite = () => {
    const [site, setSite] = useState<Site>({
        id: 0,
        name: "",
        description: "",
        networks: []
    });
    const [siteId, setSiteId] = useState<number>(0);
    const [loading, setLoading] = useState(false);
    const [currentPage, setCurrentPage] = useState(1);
    const [itemPerPage, setItemPerPage] = useState(() => {
        const savedValue = Cookies.get('sites-itemPerPage');
        return savedValue ? parseInt(savedValue, 10) : 5;
    });
    const [total, setTotal] = useState(0);
    const [search, setSearch] = useState("");
    const [sites, setSites] = useState([]);

    const loadSite = useCallback(() => {
        if (!siteId) return;
        setLoading(true);
        axios.get('/api/sites/get', {
            params: { siteId: siteId }
        }).then((response) => {
            setSite(response.data.site);
            setLoading(false);
        });
    }, [siteId]);

    const updateSite = useCallback(() => {
        if (!siteId) return;
        axios.get('/api/sites/get', {
            params: { siteId: siteId }
        }).then((response) => {
            setSite(response.data.site);
        });
    }, [siteId]);
    

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

    const editSite = (site: Site): Promise<string> | string => {
        if (!site.id) {
            return 'Site ID is required';
        }

        if(site.name.length < 3) {
            return 'Site name must be at least 3 characters long';
        }
        return axios.post('/api/sites/edit', site)
        .then(() => {
            return "Site edited successfully";
        })
        .catch(err => {
            throw err.response?.data?.error || 'An error occurred';
        });
    };

    const addSite = (site: Site): Promise<Site> | string => {
        if(site.name.length < 3) {
            return 'Site name must be at least 3 characters long';
        }
        
        return axios.post('/api/sites/add', site)
        .then((response) => {
            return response.data.site;
        })
        .catch(err => {
            throw err.response?.data?.error || 'An error occurred';
        });
    };

    const deleteSite = (siteId: number) => {
        axios.delete('/api/sites/delete', {
            params: { siteId: siteId }
        })
        .then(() => {
            setSiteId(0);
        })
        .catch(err => {
            console.error(err);
        })
    };

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

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


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

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


    return {
        site,
        loadSite,
        setSiteId,
        updateSite,
        editSite,
        addSite,
        deleteSite,
        loading,
        sites,
        currentPage,
        itemPerPage,
        total,
        search,
        setSearch,
        handlePageChange,
        setItemPerPage,
        loadSites
    };
};

export default useSite;