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

const useSite = () => {
    const [site, setSite] = useState<Site>({
        id: "",
        name: "",
        description: "",
        networks: []
    });
    const [siteId, setSiteId] = useState("");

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

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

    const editSite = (site: Site) => {
        axios.post('/api/sites/edit', site)
        .then(() => {
            console.log("Site edited successfully");
        })
        .catch(err => {
            console.error(err);
        })
    };

    const deleteSite = (siteId: string) => {
        axios.delete('/api/sites/delete', {
            params: { siteId }
        })
        .then(() => {
            setSiteId('');
        })
        .catch(err => {
            console.error(err);
        })
    };
    return {
        site,
        loadSite,
        setSiteId,
        editSite,
        deleteSite,
    };
};

export default useSite;