import { writable } from 'svelte/store';
import type { MedusaProduct, MedusaVariant } from '$lib/types/medusa';
import toast from 'svelte-french-toast';
import type { Region } from './region';
import { PUBLIC_MEDUSA_KEY } from '$env/static/public';

export interface CartItem {
    product: MedusaProduct;
    variant: MedusaVariant;
    quantity: number;
}

export const cartId = writable<string | null>(null);
export const cartItems = writable<any[]>([]);
export const cartIsOpen = writable(false);

function getStoredCartId() {
    if (typeof window === 'undefined') return null;
    return localStorage.getItem('cart_id');
}

function setStoredCartId(id: string) {
    localStorage.setItem('cart_id', id);
    cartId.set(id);
}

async function initCart() {
    const existing = getStoredCartId();
    if (existing) {
        cartId.set(existing);
        await syncCartFromBackend(existing);
    } else {
        const res = await fetch('http://localhost:9000/store/carts', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'x-publishable-api-key': PUBLIC_MEDUSA_KEY
            }
        });
        if (res.ok) {
            const { cart } = await res.json();
            setStoredCartId(cart.id);
        }
    }
}

async function syncCartFromBackend(id: string) {
    const res = await fetch(`http://localhost:9000/store/carts/${id}`, {
        headers: {
            'x-publishable-api-key': PUBLIC_MEDUSA_KEY
        }
    });
    if (res.ok) {
        const { cart } = await res.json();
        cartItems.set(cart.items || []);
        return cart;
    }
    return null;
}

function showAddToCartToast(title: string) {
    toast(`${title} added to cart`, {
        icon: '🛍️',
        duration: 2000,
        position: 'bottom-center',
        style: 'background-color: #000; color: #fff;',
    });
}

async function addItemToCart(variant_id: string, quantity = 1) {
    const id = getStoredCartId();
    if (!id) {
        await initCart();
        return addItemToCart(variant_id, quantity);
    }

    const res = await fetch(`http://localhost:9000/store/carts/${id}/line-items`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-publishable-api-key': PUBLIC_MEDUSA_KEY
        },
        body: JSON.stringify({ variant_id, quantity })
    });

    if (res.ok) {
        const cart = await syncCartFromBackend(id);
        const addedItem = cart?.items?.find((item: any) => item.variant_id === variant_id);
        if (addedItem) {
            showAddToCartToast(addedItem.title);
        }
    }
}

async function updateItemQuantity(item_id: string, quantity: number) {
    const id = getStoredCartId();
    if (!id || quantity < 1) return;

    const res = await fetch(`http://localhost:9000/store/carts/${id}/line-items/${item_id}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-publishable-api-key': PUBLIC_MEDUSA_KEY
        },
        body: JSON.stringify({ quantity })
    });

    if (res.ok) await syncCartFromBackend(id);
}

async function removeItem(item_id: string) {
    const id = getStoredCartId();
    if (!id) return;

    const res = await fetch(`http://localhost:9000/store/carts/${id}/line-items/${item_id}`, {
        method: 'DELETE',
        headers: {
            'x-publishable-api-key': PUBLIC_MEDUSA_KEY
        }
    });

    if (res.ok) await syncCartFromBackend(id);
}

export const cart = {
    init: initCart,
    add: addItemToCart,
    update: updateItemQuantity,
    remove: removeItem,
    toggle: () => cartIsOpen.update(v => !v),
    open: () => cartIsOpen.set(true),
    close: () => cartIsOpen.set(false),
    subscribe: cartItems.subscribe,
    subscribeToOpen: cartIsOpen.subscribe,
    sync: syncCartFromBackend
};

function createRegionStore() {
    const { subscribe, set, update } = writable<Region>();
    if (typeof window !== 'undefined') {
        const savedRegion = localStorage.getItem('selectedRegion');
        if (savedRegion) {
            set(JSON.parse(savedRegion));
        }
    }
    return {
        subscribe,
        setRegion: (region: Region) => set(region),
    };
}

export const region = createRegionStore();