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

import { getToken } from '../../utils/auth'
import { API_URL } from '../../config'
import { isObject } from '../../utils/types'
import { handleHTTPErrors } from '../../utils'

type BookResponse = {
    Success: boolean
}

const isBookResponse = (obj: unknown): obj is BookResponse => isObject(obj, {
    'Success': 'boolean'
})

type BookStatus = '' | 'Загрузка...' | 'Забронировано' | 'Ошибка бронирования'

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

    const [status, setStatus] = useState<BookStatus>('')

    const handleBook = async () => {
        const token = getToken()

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

            try {

                const res = await fetch(API_URL + '/book', {
                    method: 'POST',
                    body: JSON.stringify({
                        id: id
                    }),
                    headers: {
                        'Authorization': 'Bearer ' + token,
                        'Content-Type': 'application/json'
                    }
                })

                handleHTTPErrors(res)

                const data: unknown = await res.json()

                if (!isBookResponse(data)) {
                    throw new Error('Malformed server response')
                }

                if (data.Success === true) {
                    setStatus('Забронировано')
                } else {
                    throw new Error('Server refused to book')
                }
            }
            catch (err) {
                setStatus('Ошибка бронирования')

                if (import.meta.env.DEV) {
                    console.log(err)
                }
            }
        } else {
            return navigate('/login')
        }
    }

    return { handleBook, status }
}

export default useBook
