import { useState } from "react"
import { useNavigate } from "react-router-dom"

import { getToken } from "../../utils/auth"
import { API_URL } from "../../config"

function useBook(id) {
    const navigate = useNavigate()

    const [status, setStatus] = useState('')

    const handleBook = () => {
        const token = getToken() || "Test"

        if (token) {
            setStatus("Загрузка")

            fetch(API_URL + '/book', {
                method: 'POST',
                body: JSON.stringify({
                    id: id
                }),
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                }
            }).then(res => res.json()).then(data => {
                if (data.Success === true) {
                    setStatus('Забронировано')
                } else {
                    setStatus("Ошибка бронирования")
                }
            })
        } else {
            return navigate("/login")
        }
    }

    return { handleBook, status }
}

export default useBook
