{# app/templates/store/order-detail.html #}
{% extends "store/base.html" %}
{% from 'shared/macros/headers.html' import page_header_flex %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/modals.html' import modal_simple %}

{% block title %}Order Details{% endblock %}

{% block alpine_data %}storeOrderDetail(){% endblock %}

{% block content %}
<!-- Back Button and Header -->
<div class="mb-6">
    <a :href="`/store/${storeCode}/orders`"
       class="inline-flex items-center text-sm text-gray-600 hover:text-purple-600 dark:text-gray-400 dark:hover:text-purple-400 mb-4">
        <span x-html="$icon('arrow-left', 'w-4 h-4 mr-1')"></span>
        Back to Orders
    </a>
</div>

{% call page_header_flex(title='Order Details', subtitle='View and manage order') %}
    <div class="flex items-center gap-2" x-show="!loading && order">
        <!-- Status Badge -->
        <span
            :class="{
                'px-3 py-1 text-sm font-semibold rounded-full': true,
                'text-yellow-700 bg-yellow-100 dark:bg-yellow-700 dark:text-yellow-100': getStatusColor(order?.status) === 'yellow',
                'text-blue-700 bg-blue-100 dark:bg-blue-700 dark:text-blue-100': getStatusColor(order?.status) === 'blue',
                'text-orange-700 bg-orange-100 dark:bg-orange-700 dark:text-orange-100': getStatusColor(order?.status) === 'orange',
                'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100': getStatusColor(order?.status) === 'green',
                'text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100': getStatusColor(order?.status) === 'red',
                'text-indigo-700 bg-indigo-100 dark:bg-indigo-700 dark:text-indigo-100': getStatusColor(order?.status) === 'indigo',
                'text-gray-700 bg-gray-100 dark:bg-gray-700 dark:text-gray-100': getStatusColor(order?.status) === 'gray'
            }"
            x-text="getStatusLabel(order?.status)"
        ></span>

        <!-- Update Status Button -->
        <button
            @click="showStatusModal = true"
            class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
        >
            <span x-html="$icon('pencil-square', 'w-4 h-4 inline mr-1')"></span>
            Update Status
        </button>
    </div>
{% endcall %}

{{ loading_state('Loading order details...') }}
{{ error_state('Error loading order') }}

<!-- Main Content -->
<div x-show="!loading && !error && order" class="grid gap-6 lg:grid-cols-3">
    <!-- Left Column: Order Info -->
    <div class="lg:col-span-2 space-y-6">
        <!-- Order Summary Card -->
        <div class="bg-white rounded-lg shadow-xs dark:bg-gray-800 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">
                    Order <span x-text="order?.order_number"></span>
                </h3>
                <p class="text-sm text-gray-500 dark:text-gray-400">
                    Placed on <span x-text="formatDateTime(order?.order_date)"></span>
                </p>
            </div>
            <div class="p-6 grid grid-cols-2 md:grid-cols-4 gap-4">
                <div>
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Channel</p>
                    <p class="text-sm font-medium text-gray-700 dark:text-gray-200 capitalize" x-text="order?.channel || 'direct'"></p>
                </div>
                <div>
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Items</p>
                    <p class="text-sm font-medium text-gray-700 dark:text-gray-200" x-text="order?.items?.length || 0"></p>
                </div>
                <div>
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Subtotal</p>
                    <p class="text-sm font-medium text-gray-700 dark:text-gray-200" x-text="formatPrice(order?.subtotal_cents)"></p>
                </div>
                <div>
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Total</p>
                    <p class="text-lg font-bold text-purple-600 dark:text-purple-400" x-text="formatPrice(order?.total_amount_cents)"></p>
                </div>
            </div>
        </div>

        <!-- Order Items -->
        <div class="bg-white rounded-lg shadow-xs dark:bg-gray-800 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Order Items</h3>
                <template x-if="shipmentStatus">
                    <span class="text-sm text-gray-500 dark:text-gray-400">
                        <span x-text="shipmentStatus.total_shipped_units"></span>/<span x-text="shipmentStatus.total_ordered_units"></span> units shipped
                    </span>
                </template>
            </div>
            <div class="divide-y divide-gray-200 dark:divide-gray-700">
                <template x-for="item in order?.items || []" :key="item.id">
                    <div class="p-4 flex items-start gap-4">
                        <!-- Product Info -->
                        <div class="flex-1">
                            <p class="font-medium text-gray-700 dark:text-gray-200" x-text="item.product_name"></p>
                            <p class="text-sm text-gray-500 dark:text-gray-400">
                                <span x-show="item.product_sku">SKU: <span x-text="item.product_sku"></span></span>
                                <span x-show="item.gtin"> | GTIN: <span x-text="item.gtin"></span></span>
                            </p>
                            <p class="text-sm text-gray-600 dark:text-gray-300 mt-1">
                                <span x-text="formatPrice(item.unit_price_cents)"></span> x <span x-text="item.quantity"></span>
                            </p>
                        </div>

                        <!-- Shipment Status -->
                        <div class="text-right">
                            <p class="font-semibold text-gray-700 dark:text-gray-200" x-text="formatPrice(item.total_price_cents)"></p>
                            <template x-if="getItemShipmentStatus(item.id)">
                                <div class="mt-1">
                                    <template x-if="getItemShipmentStatus(item.id).is_fully_shipped">
                                        <span class="px-2 py-0.5 text-xs font-medium text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">
                                            Shipped
                                        </span>
                                    </template>
                                    <template x-if="getItemShipmentStatus(item.id).is_partially_shipped">
                                        <span class="px-2 py-0.5 text-xs font-medium text-orange-700 bg-orange-100 rounded-full dark:bg-orange-700 dark:text-orange-100">
                                            <span x-text="getItemShipmentStatus(item.id).shipped_quantity"></span>/<span x-text="getItemShipmentStatus(item.id).quantity"></span> shipped
                                        </span>
                                    </template>
                                    <template x-if="!getItemShipmentStatus(item.id).is_fully_shipped && !getItemShipmentStatus(item.id).is_partially_shipped">
                                        <span class="px-2 py-0.5 text-xs font-medium text-gray-700 bg-gray-100 rounded-full dark:bg-gray-700 dark:text-gray-100">
                                            Pending
                                        </span>
                                    </template>
                                </div>
                            </template>

                            <!-- Ship Item Button -->
                            <template x-if="canShipItem(item.id) && order?.status !== 'shipped'">
                                <button
                                    @click="shipItem(item.id)"
                                    :disabled="saving"
                                    class="mt-2 px-3 py-1 text-xs font-medium text-white bg-indigo-600 rounded hover:bg-indigo-700 disabled:opacity-50"
                                >
                                    <span x-html="$icon('truck', 'w-3 h-3 inline mr-1')"></span>
                                    Ship
                                </button>
                            </template>
                        </div>
                    </div>
                </template>
            </div>

            <!-- Totals -->
            <div class="px-6 py-4 bg-gray-50 dark:bg-gray-700 border-t border-gray-200 dark:border-gray-600">
                <div class="space-y-2 text-sm">
                    <div class="flex justify-between">
                        <span class="text-gray-600 dark:text-gray-400">Subtotal</span>
                        <span class="text-gray-700 dark:text-gray-200" x-text="formatPrice(order?.subtotal_cents)"></span>
                    </div>
                    <div class="flex justify-between" x-show="order?.tax_amount_cents">
                        <span class="text-gray-600 dark:text-gray-400">Tax</span>
                        <span class="text-gray-700 dark:text-gray-200" x-text="formatPrice(order?.tax_amount_cents)"></span>
                    </div>
                    <div class="flex justify-between" x-show="order?.shipping_amount_cents">
                        <span class="text-gray-600 dark:text-gray-400">Shipping</span>
                        <span class="text-gray-700 dark:text-gray-200" x-text="formatPrice(order?.shipping_amount_cents)"></span>
                    </div>
                    <div class="flex justify-between" x-show="order?.discount_amount_cents">
                        <span class="text-gray-600 dark:text-gray-400">Discount</span>
                        <span class="text-green-600 dark:text-green-400">-<span x-text="formatPrice(order?.discount_amount_cents)"></span></span>
                    </div>
                    <div class="flex justify-between pt-2 border-t border-gray-200 dark:border-gray-600 font-semibold">
                        <span class="text-gray-700 dark:text-gray-200">Total</span>
                        <span class="text-purple-600 dark:text-purple-400" x-text="formatPrice(order?.total_amount_cents)"></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tracking Info -->
        <div class="bg-white rounded-lg shadow-xs dark:bg-gray-800 overflow-hidden" x-show="order?.tracking_number || order?.shipped_at">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Shipping & Tracking</h3>
            </div>
            <div class="p-6 grid grid-cols-2 gap-4">
                <div x-show="order?.tracking_provider">
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Carrier</p>
                    <p class="text-sm font-medium text-gray-700 dark:text-gray-200" x-text="order?.tracking_provider"></p>
                </div>
                <div x-show="order?.tracking_number">
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Tracking Number</p>
                    <p class="text-sm font-medium text-gray-700 dark:text-gray-200" x-text="order?.tracking_number"></p>
                </div>
                <div x-show="order?.shipped_at">
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase">Shipped At</p>
                    <p class="text-sm font-medium text-gray-700 dark:text-gray-200" x-text="formatDateTime(order?.shipped_at)"></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column: Customer & Actions -->
    <div class="space-y-6">
        <!-- Customer Info -->
        <div class="bg-white rounded-lg shadow-xs dark:bg-gray-800 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Customer</h3>
            </div>
            <div class="p-6 space-y-4">
                <div>
                    <p class="font-medium text-gray-700 dark:text-gray-200" x-text="`${order?.customer_first_name || ''} ${order?.customer_last_name || ''}`"></p>
                    <p class="text-sm text-gray-500 dark:text-gray-400" x-text="order?.customer_email"></p>
                    <p class="text-sm text-gray-500 dark:text-gray-400" x-text="order?.customer_phone" x-show="order?.customer_phone"></p>
                </div>
            </div>
        </div>

        <!-- Shipping Address -->
        <div class="bg-white rounded-lg shadow-xs dark:bg-gray-800 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Shipping Address</h3>
            </div>
            <div class="p-6">
                <p class="text-sm text-gray-700 dark:text-gray-200" x-text="`${order?.ship_first_name || ''} ${order?.ship_last_name || ''}`"></p>
                <p class="text-sm text-gray-500 dark:text-gray-400" x-text="order?.ship_company" x-show="order?.ship_company"></p>
                <p class="text-sm text-gray-500 dark:text-gray-400" x-text="order?.ship_address_line_1"></p>
                <p class="text-sm text-gray-500 dark:text-gray-400" x-text="order?.ship_address_line_2" x-show="order?.ship_address_line_2"></p>
                <p class="text-sm text-gray-500 dark:text-gray-400">
                    <span x-text="order?.ship_postal_code"></span> <span x-text="order?.ship_city"></span>
                </p>
                <p class="text-sm text-gray-500 dark:text-gray-400" x-text="order?.ship_country_iso"></p>
            </div>
        </div>

        <!-- Invoice Section -->
        <div class="bg-white rounded-lg shadow-xs dark:bg-gray-800 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Invoice</h3>
            </div>
            <div class="p-6">
                <template x-if="invoice">
                    <div>
                        <p class="text-sm text-gray-700 dark:text-gray-200">
                            <span x-text="invoice.invoice_number"></span>
                        </p>
                        <p class="text-xs text-gray-500 dark:text-gray-400 mb-3">
                            Status: <span class="capitalize" x-text="invoice.status"></span>
                        </p>
                        <div class="flex gap-2">
                            <a
                                :href="`/store/${storeCode}/invoices?invoice_id=${invoice.id}`"
                                class="px-3 py-1.5 text-xs font-medium text-purple-600 bg-purple-100 rounded hover:bg-purple-200 dark:bg-purple-900 dark:text-purple-300"
                            >
                                View Invoice
                            </a>
                            <button
                                @click="downloadInvoicePdf()"
                                :disabled="downloadingPdf"
                                class="px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 rounded hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 disabled:opacity-50"
                            >
                                <span x-show="!downloadingPdf">Download PDF</span>
                                <span x-show="downloadingPdf">Downloading...</span>
                            </button>
                        </div>
                    </div>
                </template>
                <template x-if="!invoice && order?.status !== 'pending'">
                    <div>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-3">No invoice created yet</p>
                        <button
                            @click="createInvoice()"
                            :disabled="creatingInvoice"
                            class="w-full px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50"
                        >
                            <span x-show="!creatingInvoice">
                                <span x-html="$icon('document-plus', 'w-4 h-4 inline mr-1')"></span>
                                Create Invoice
                            </span>
                            <span x-show="creatingInvoice">Creating...</span>
                        </button>
                    </div>
                </template>
                <template x-if="!invoice && order?.status === 'pending'">
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                        Confirm the order first before creating an invoice
                    </p>
                </template>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="bg-white rounded-lg shadow-xs dark:bg-gray-800 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Quick Actions</h3>
            </div>
            <div class="p-4 space-y-2">
                <template x-if="order?.status === 'pending'">
                    <button
                        @click="updateOrderStatus('processing')"
                        :disabled="saving"
                        class="w-full px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50"
                    >
                        <span x-html="$icon('check-circle', 'w-4 h-4 inline mr-1')"></span>
                        Confirm Order
                    </button>
                </template>
                <template x-if="order?.status === 'processing' || order?.status === 'partially_shipped'">
                    <button
                        @click="showShipAllModal = true"
                        :disabled="saving"
                        class="w-full px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 disabled:opacity-50"
                    >
                        <span x-html="$icon('truck', 'w-4 h-4 inline mr-1')"></span>
                        Ship All Remaining
                    </button>
                </template>
                <template x-if="order?.status === 'shipped'">
                    <button
                        @click="updateOrderStatus('delivered')"
                        :disabled="saving"
                        class="w-full px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700 disabled:opacity-50"
                    >
                        <span x-html="$icon('check', 'w-4 h-4 inline mr-1')"></span>
                        Mark as Delivered
                    </button>
                </template>
                <template x-if="!['cancelled', 'refunded', 'delivered'].includes(order?.status)">
                    <button
                        @click="updateOrderStatus('cancelled')"
                        :disabled="saving"
                        class="w-full px-4 py-2 text-sm font-medium text-red-600 bg-red-100 rounded-lg hover:bg-red-200 disabled:opacity-50 dark:bg-red-900 dark:text-red-300 dark:hover:bg-red-800"
                    >
                        <span x-html="$icon('x-circle', 'w-4 h-4 inline mr-1')"></span>
                        Cancel Order
                    </button>
                </template>
            </div>
        </div>

        <!-- Notes -->
        <div class="bg-white rounded-lg shadow-xs dark:bg-gray-800 overflow-hidden" x-show="order?.customer_notes || order?.internal_notes">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg font-semibold text-gray-700 dark:text-gray-200">Notes</h3>
            </div>
            <div class="p-6 space-y-4">
                <div x-show="order?.customer_notes">
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase mb-1">Customer Notes</p>
                    <p class="text-sm text-gray-700 dark:text-gray-200" x-text="order?.customer_notes"></p>
                </div>
                <div x-show="order?.internal_notes">
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase mb-1">Internal Notes</p>
                    <p class="text-sm text-gray-700 dark:text-gray-200" x-text="order?.internal_notes"></p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Status Update Modal -->
{% call modal_simple('updateOrderStatusModal', 'Update Order Status', show_var='showStatusModal', size='sm') %}
<div class="space-y-4">
    <div>
        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">New Status</label>
        <select
            x-model="newStatus"
            class="w-full px-4 py-2 text-sm text-gray-700 bg-gray-50 border border-gray-200 rounded-lg dark:text-gray-300 dark:bg-gray-700 dark:border-gray-600 focus:border-purple-400 focus:outline-none focus:ring-1 focus:ring-purple-400"
        >
            <template x-for="status in statuses" :key="status.value">
                <option :value="status.value" x-text="status.label"></option>
            </template>
        </select>

        <!-- Tracking Info (shown when shipping) -->
        <template x-if="newStatus === 'shipped'">
            <div class="mt-4 space-y-3">
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Tracking Number</label>
                    <input
                        type="text"
                        x-model="trackingNumber"
                        placeholder="Enter tracking number"
                        class="w-full px-3 py-2 text-sm border rounded-lg focus:border-purple-400 focus:outline-none focus:ring-1 focus:ring-purple-400 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
                    />
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Carrier</label>
                    <input
                        type="text"
                        x-model="trackingProvider"
                        placeholder="e.g., DHL, PostNL"
                        class="w-full px-3 py-2 text-sm border rounded-lg focus:border-purple-400 focus:outline-none focus:ring-1 focus:ring-purple-400 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
                    />
                </div>
            </div>
        </template>
    </div>
    <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
        <button
            @click="showStatusModal = false"
            class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
        >Cancel</button>
        <button
            @click="confirmStatusUpdate()"
            :disabled="saving"
            class="px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50"
        >Update</button>
    </div>
</div>
{% endcall %}

<!-- Ship All Modal -->
{% call modal_simple('shipAllModal', 'Ship All Items', show_var='showShipAllModal', size='sm') %}
<div class="space-y-4">
    <p class="text-sm text-gray-600 dark:text-gray-400">
        This will ship all remaining items and mark the order as shipped.
    </p>
    <div>
        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Tracking Number</label>
        <input
            type="text"
            x-model="trackingNumber"
            placeholder="Enter tracking number"
            class="w-full px-3 py-2 text-sm border rounded-lg focus:border-purple-400 focus:outline-none focus:ring-1 focus:ring-purple-400 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
        />
    </div>
    <div>
        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Carrier</label>
        <input
            type="text"
            x-model="trackingProvider"
            placeholder="e.g., DHL, PostNL"
            class="w-full px-3 py-2 text-sm border rounded-lg focus:border-purple-400 focus:outline-none focus:ring-1 focus:ring-purple-400 dark:bg-gray-700 dark:border-gray-600 dark:text-gray-200"
        />
    </div>
    <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
        <button
            @click="showShipAllModal = false"
            class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
        >Cancel</button>
        <button
            @click="shipAllItems()"
            :disabled="saving"
            class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50"
        >Ship All</button>
    </div>
</div>
{% endcall %}
{% endblock %}

{% block extra_scripts %}
<script>
    // Pass order ID to JavaScript
    window.orderDetailData = {
        orderId: {{ order_id }}
    };
</script>
<script defer src="{{ url_for('orders_static', path='store/js/order-detail.js') }}"></script>
{% endblock %}
