<script lang="ts">
    import { cartItems } from '$lib/stores/cart';
    import { region } from '$lib/stores/cart';
    import { PUBLIC_MEDUSA_KEY } from '$env/static/public';
    import { onMount } from 'svelte';

    let formData = {
        firstName: '',
        lastName: '',
        email: '',
        country: '',
        phoneNumber: '',
        district: '',
        block: '',
        street: '',
        avenue: '',
        buildingNumber: ''
    };

    let shippingOptions: any[] = [];
    let selectedShippingOption: string | null = null;
    let isLoadingShipping = true;

    onMount(async () => {
        await loadShippingOptions();
    });

    async function loadShippingOptions() {
        try {
            isLoadingShipping = true;
            let cartId = localStorage.getItem('cart_id');
            const response = await fetch(`http://localhost:9000/store/shipping-options?cart_id=${cartId}`, {
                headers: {
                    'x-publishable-api-key': PUBLIC_MEDUSA_KEY,
                },
            });
            const data = await response.json();
            shippingOptions = data.shipping_options;
            
            // If there's only one option, select it automatically
            if (shippingOptions.length === 1) {
                selectedShippingOption = shippingOptions[0].id;
            }
        } catch (error) {
            console.error('Error loading shipping options:', error);
        } finally {
            isLoadingShipping = false;
        }
    }

    function handleSubmit() {
        if (!selectedShippingOption) {
            alert('Please select a shipping option');
            return;
        }
        // Here you'll integrate payment processing later
        console.log('Form submitted:', {
            ...formData,
            shippingOptionId: selectedShippingOption
        });
        console.log('Cart items:', $cartItems);
    }

    function calculateItemTotal(item: any) {
        return (item.unit_price * item.quantity).toFixed(2);
    }

    function calculateTotal(items: any[]) {
        return items.reduce((sum, item) => 
            sum + (item.unit_price * item.quantity), 0
        ).toFixed(2);
    }

    function getCurrencySymbol(currency_code: string) {
        switch (currency_code?.toLowerCase()) {
            case 'eur':
                return '€';
            case 'usd':
                return '$';
            case 'kwd':
                return 'KWD';
            default:
                return currency_code?.toUpperCase() || '';
        }
    }

    let currencyCode = $region?.currency_code || 'KWD';
    let currencySymbol = getCurrencySymbol(currencyCode);
</script>

<div class="min-h-screen bg-base-100">
    <div class="container mx-auto px-4 py-8">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Order Summary -->
            <div class="lg:col-span-1 h-fit bg-base-200 rounded-lg p-6">
                <h2 class="text-xl font-bold mb-4">Order Summary</h2>
                <div class="space-y-3 mb-4">
                    {#each $cartItems as item}
                        <div class="flex justify-between items-start text-sm border-b border-base-300 pb-2">
                            <div class="flex-1">
                                <p class="font-medium">{item.title}</p>
                                <p class="text-xs text-base-content/70">
                                    {#if item.variant && item.variant.title}
                                        {item.variant.title}
                                    {/if}
                                    × {item.quantity}
                                </p>
                            </div>
                            <p class="font-medium ml-4">{calculateItemTotal(item)} {currencySymbol}</p>
                        </div>
                    {/each}
                </div>

                <!-- Shipping Options -->
                <div class="mb-4">
                    <h3 class="font-medium mb-2">Shipping Method</h3>
                    {#if isLoadingShipping}
                        <div class="w-full h-12 flex items-center justify-center">
                            <span class="loading loading-spinner loading-sm"></span>
                        </div>
                    {:else if shippingOptions.length === 0}
                        <div class="alert alert-warning alert-sm">
                            No shipping options available
                        </div>
                    {:else}
                        <div class="space-y-2">
                            {#each shippingOptions as option}
                                <label class="flex items-center gap-3 p-2 border rounded-lg cursor-pointer hover:bg-base-300 transition-colors {selectedShippingOption === option.id ? 'bg-base-300 border-primary' : 'bg-base-100'}">
                                    <input
                                        type="radio"
                                        name="shipping_option"
                                        value={option.id}
                                        bind:group={selectedShippingOption}
                                        class="radio radio-primary radio-sm"
                                    />
                                    <div class="flex-1">
                                        <p class="text-sm font-medium">{option.name}</p>
                                        {#if option.data}
                                            <p class="text-xs text-base-content/70">{option.data.id}</p>
                                        {/if}
                                    </div>
                                    <!-- {#if option.insufficient_inventory}
                                        <span class="badge badge-warning badge-sm">Limited Stock</span>
                                    {/if} -->
                                </label>
                            {/each}
                        </div>
                    {/if}
                </div>
                
                <div class="flex justify-between items-center pt-4 border-t">
                    <span class="text-lg font-bold">Total:</span>
                    <span class="text-lg font-bold">{calculateTotal($cartItems)} {currencySymbol}</span>
                </div>
            </div>

            <!-- Shipping Details Form -->
            <form class="lg:col-span-2 space-y-6 bg-base-200 rounded-lg p-6" on:submit|preventDefault={handleSubmit}>
                <h2 class="text-xl font-bold">Shipping Details</h2>
                
                <div class="grid grid-cols-2 gap-4">
                    <div class="form-control">
                        <label class="label" for="firstName">
                            <span class="label-text">First Name</span>
                        </label>
                        <input 
                            type="text" 
                            id="firstName"
                            class="input input-bordered w-full" 
                            bind:value={formData.firstName} 
                            placeholder="John"
                            required
                        />
                    </div>

                    <div class="form-control">
                        <label class="label" for="lastName">
                            <span class="label-text">Last Name</span>
                        </label>
                        <input 
                            type="text" 
                            id="lastName"
                            class="input input-bordered w-full" 
                            bind:value={formData.lastName} 
                            placeholder="Doe"
                            required
                        />
                    </div>
                </div>

                <div class="form-control">
                    <label class="label" for="email">
                        <span class="label-text">Email</span>
                    </label>
                    <input 
                        type="email" 
                        id="email"
                        class="input input-bordered w-full" 
                        bind:value={formData.email} 
                        placeholder="john.doe@example.com"
                        required
                    />
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div class="form-control">
                        <label class="label" for="country">
                            <span class="label-text">Country</span>
                        </label>
                        <input 
                            type="text" 
                            id="country"
                            class="input input-bordered w-full" 
                            bind:value={formData.country} 
                            placeholder="Kuwait"
                            required
                        />
                    </div>

                    <div class="form-control">
                        <label class="label" for="phoneNumber">
                            <span class="label-text">Phone Number</span>
                        </label>
                        <input 
                            type="tel" 
                            id="phoneNumber"
                            class="input input-bordered w-full" 
                            bind:value={formData.phoneNumber} 
                            placeholder="+96596596596"
                            required
                        />
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div class="form-control">
                        <label class="label" for="district">
                            <span class="label-text">District</span>
                        </label>
                        <input 
                            type="text" 
                            id="district"
                            class="input input-bordered w-full" 
                            bind:value={formData.district} 
                            placeholder="Al-Rai"
                            required
                        />
                    </div>

                    <div class="form-control">
                        <label class="label" for="block">
                            <span class="label-text">Block</span>
                        </label>
                        <input 
                            type="text" 
                            id="block"
                            class="input input-bordered w-full" 
                            bind:value={formData.block} 
                            placeholder="2"
                            required
                        />
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div class="form-control">
                        <label class="label" for="street">
                            <span class="label-text">Street</span>
                        </label>
                        <input 
                            type="text" 
                            id="street"
                            class="input input-bordered w-full" 
                            bind:value={formData.street} 
                            placeholder="203"
                            required
                        />
                    </div>

                    <div class="form-control">
                        <label class="label" for="avenue">
                            <span class="label-text">Avenue (optional)</span>
                        </label>
                        <input 
                            type="text" 
                            id="avenue"
                            class="input input-bordered w-full" 
                            bind:value={formData.avenue}
                            placeholder="31"
                        />
                    </div>
                </div>

                <div class="form-control">
                    <label class="label" for="buildingNumber">
                        <span class="label-text">Building Number</span>
                    </label>
                    <input 
                        type="text" 
                        id="buildingNumber"
                        class="input input-bordered w-full" 
                        bind:value={formData.buildingNumber} 
                        placeholder="12"
                        required
                    />
                </div>

                <button type="submit" class="btn btn-primary w-full">
                    Continue to Payment
                </button>
            </form>
        </div>
    </div>
</div> 