import { useEffect, useState } from "react";
import type { Product, ProductResponse } from "../types";
import type { CartSession } from "../types/cart";

const apiEndpoint = 'https://web-ecommerce.web-055.workers.dev';

const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uSWQiOiIyZWFmYTE0NS0xMWUwLTQ2ZDctODI3ZS03ZjczNzAzODJjNjUiLCJleHAiOjE5MjE4Mjk2MTR9.1vEBPmjEBGltJk5TYLjZLBtHasENWLFb4VwAf-hsgiE";

export const usePictarineApi = () => {

	const [products, setProducts] = useState<Product[] | undefined>(undefined);
	const [productsLoading, setProductsLoading] = useState<boolean>(false);
	const [productsError, setProductsError] = useState<Error | undefined>(undefined);

	const [cart, setCart] = useState<CartSession | undefined>(undefined)
	const [cartLoading, setCartLoading] = useState<boolean>(false)
	const [cartError, setCartError] = useState<Error | undefined>(undefined)

	useEffect(() => {
		(async () => {

			try { 
				setProductsLoading(true);			
				setProductsError(undefined);			
				const response = await fetch(`${apiEndpoint}/products`);
				const json = await response.json() as ProductResponse;
				setProductsLoading(false);			
				setProducts(json.products);
			} catch(error) {
				setProductsError(error as Error);
			}

		})()			
	}, [])

	const reloadCart = async () => {

		try { 
			setCartLoading(true);			
			setCartError(undefined);			
			const response = await fetch(`${apiEndpoint}/cart`, {
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`
				}});
			const json = await response.json() as CartSession;
			setCartLoading(false);			
			setCart(json);
		} catch(error) {
			setCartError(error as Error);
		}

	}

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

	const addToCart = async (productId: string, quantity: number) => {
		
		try { 
			setCartLoading(true);
			await fetch(`${apiEndpoint}/cart/add`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`
				},
				body: JSON.stringify({
					productId,
					quantity
				})
			})
			reloadCart();
		} catch(error) {
			setCartError(error as Error);
		}
		

	}

	const updateCartQuantity = async (productId: string, quantity: number) => {
		
		try { 
			setCartLoading(true);
			await fetch(`${apiEndpoint}/cart/update`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`
				},
				body: JSON.stringify({
					productId,
					quantity
				})
			})
			reloadCart();
		} catch(error) {
			setCartError(error as Error);
		}

	}

	const removeItemFromCart = async (productId: string) => {
		try { 
			setCartLoading(true);
			await fetch(`${apiEndpoint}/cart/remove`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`
				},
				body: JSON.stringify({
					productId,
				})
			})
			reloadCart();
		} catch(error) {
			setCartError(error as Error);
		}

	}

	const clearCart = async () => {
		try { 
			setCartLoading(true);
			await fetch(`${apiEndpoint}/cart/clear`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					Authorization: `Bearer ${token}`
				},
			})
			reloadCart();
		} catch(error) {
			setCartError(error as Error);
		}

	}

	return {
		products, 
		productsLoading,
		productsError,
		cart,
		cartError,
		cartLoading,
		addToCart,
		updateCartQuantity,
		removeItemFromCart,
		clearCart
	}
}
