import { useState, useEffect } from 'react';
import type { Hosting } from '../types';
import { API_URL } from '../constants/constants';

const useFetchHosting = () => {
    const [data, setData] = useState<Hosting|null>(null);
    const [error, setError] = useState<string | null>(null);
    const [loading, setLoading] = useState(false);

    const fetchData = async () => {
        setLoading(true);
        setError(null);
        try {
            const response = await fetch(`${API_URL}/hosting`);
            if (response.status != 200) {
                throw new Error('Network response was not ok');
            }
            const result = await response.json();
            setData(result);
        } finally {
            setLoading(false);
        }
    };

    const updateData = async (name: string, id: number) => {
        setLoading(true);
        setError(null);
        try {
            const response = await fetch(`${API_URL}/hosting/${id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ reservedBy: name })
            });

            if (!response.ok) { // Check for non-200 responses
                const errorText = await response.text(); // Capture the response text for further insights
                throw new Error(`Error ${response.status}: ${errorText}`);
            }

            // Optional: Fetch the updated data after reservation
            await fetchData();
        } finally {
            setLoading(false);
        }
    };

    const unreserveHosting = async (token: string, id: number) => {
        setLoading(true);
        setError(null);
        try {
            const response = await fetch(`${API_URL}/hosting/${id}/unreserve`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ token })
            });

            if (!response.ok) { // Check for non-200 responses
                const errorText = await response.text(); // Capture the response text for further insights
                throw new Error(`Error ${response.status}: ${errorText}`);
            }

            // Optional: Fetch the updated data after reservation
            await fetchData();
        } finally {
            setLoading(false);
        }
    };

    const createHosting = async (token: string, name: string, capacity: number) => {
        setError(null);
        try {
            const response = await fetch(`${API_URL}/hosting/create`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ token, name, capacity })
            });

            if (!response.ok) { // Check for non-200 responses
                const errorText = await response.text(); // Capture the response text for further insights
                console.log(`Error ${response.status}: ${errorText}`)
                throw new Error(`Error ${response.status}: ${errorText}`);
            }

            // Optional: Fetch the updated data after reservation
            await fetchData();
        } finally {
        }
    };


    useEffect(() => {
        fetchData(); // Initial fetch on mount
    }, []);

    return { data, error, loading, refetch: fetchData, update: updateData, unreserveHosting, createHosting};
};

export default useFetchHosting;
