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): string | void => {
        if (!site.id) {
            return 'Site ID is required';
        }

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

    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;