import { storeToRefs } from "pinia";
import { useLoginStore } from "../auth/login/login.store";
import type { ProductInterface } from "../products/interfaces/products.interface";
import { useProductStore } from "../useProductStore";
import type { AddToCartInterface } from "./interfaces/add_to_cart.interface";
import axios from "axios";
import { useProductsStore } from "../products/products.store";

export const useCartStore = defineStore("cart", () => {

    const userStore = useLoginStore();
    const productsStore = useProductsStore();
    
    const runtimeConfig = useRuntimeConfig();
    const cart_products = ref(null);
    const cart_off_canvas = ref<boolean>(false);
    const order_quantity = ref<number>(1);
    const route = useRoute();

    /**
     * Obtiene el carrito
     * @returns 
     */
    const getCart = async () => {
        try {
            const access_token = useCookie('access_token').value || '';
            
            const response = await axios.get(`${runtimeConfig.public.api_url}/api/cart`,
                { headers: { Authorization: access_token ? `Bearer ${access_token}` : '' } }
            );

            if(response.data) {
                cart_products.value = response.data;
                console.log(response.data, ' cartProducts');
                return response.data;
            } else {
                return null;
            }
        } catch (error) {
            return null;
        }
    }

    /**
     * Agrega un producto a un carrito
     * @param payload 
     * @returns 
     */
    const addCartProduct = async (payload: AddToCartInterface) => {
        try {
            const access_token = useCookie('access_token').value || '';

            const response = await axios.post(`${runtimeConfig.public.api_url}/api/cart/cart_item/add`,
                { ...payload, quantity: order_quantity.value },
                { headers: { Authorization: access_token ? `Bearer ${access_token}` : '' } }
            );
            if (response.data) {
                userStore.user.products_in_cart = await getTotalCartItems();
                return { added: true, data: response.data, message: '' }
            } else {
                return { added: false, data: null, message: 'Hubo un error al agregar el producto.' }
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                if (error.status == 401) {
                    navigateTo('/login')
                } else if (error.response.data.cause && error.response.data.cause.includes('PRODUCT_ADDED')) {
                    return { added: false, data: null, message: "El producto ya ha sido agregado." }
                } else {
                    return { added: false, data: null, message: 'Hubo un error al agregar el producto.' }
                }
            } else {
                return { added: false, data: null, message: 'Hubo un error al agregar el producto.' }
            }
        }
    };

    /**
     * Elimina un producto del carrito
     * @param item_id 
     * @returns 
     */
    const removeCartItem = async (item_id: number) => {
        try {
            const access_token = useCookie('access_token').value || '';

            const response = await axios.delete(`${runtimeConfig.public.api_url}/api/cart/cart_item/${item_id}`,
                { headers: { Authorization: access_token ? `Bearer ${access_token}` : '' } }
            );

            if(response.data) {
                userStore.user.products_in_cart = await getTotalCartItems();
                if(productsStore.product) {
                    productsStore.product.exist_in_cart = false;
                }
                return true;
            } else {
                return false;
            }

        } catch (error) {
            console.error(error);
            return false;
        }
    }

    /**
     * Obtiene el total de productos que hay en el carrito
     * @returns 
     */
    const getTotalCartItems = async (): Promise<number> => {
        try {
            const access_token = useCookie('access_token').value || '';

            const response = await axios.get<{total: number}>(`${runtimeConfig.public.api_url}/api/cart/total_items`,
                { headers: { Authorization: access_token ? `Bearer ${access_token}` : '' } }
            );

            if (response.data) {
                return response.data.total;
            } else {
                return 0
            }
        } catch (error) {
            return 0;
        }
    }

    // quantity increment
    const increment = () => {
        return order_quantity.value = order_quantity.value + 1;
    }

    const decrement = () => {
        return order_quantity.value =
            order_quantity.value > 1
                ? order_quantity.value - 1
                : (order_quantity.value = 1);
    }

    //handle cartOffcanvas
    const handleCartOffcanvas = async () => {
        cart_off_canvas.value = !cart_off_canvas.value;
        if(cart_off_canvas.value) {
            await getCart();
        }
    }

    return {
        getCart,
        addCartProduct,
        increment,
        decrement,
        handleCartOffcanvas,
        removeCartItem,

        cart_products,
        order_quantity,
        cart_off_canvas,
    }
})