<x-layouts.admin title="Inventory">
    <x-admin.page-header title="Inventory" subtitle="Stock by color and size across the catalog." />

    <div class="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-3">
        <x-admin.stat-card label="Variants Tracked" :value="$counts['total_variants']" icon="fa-solid fa-boxes-stacked" accent="champagne" />
        <x-admin.stat-card label="Low Stock" :value="$counts['low_stock']" icon="fa-solid fa-triangle-exclamation" accent="warning" />
        <x-admin.stat-card label="Out of Stock" :value="$counts['out_of_stock']" icon="fa-solid fa-circle-xmark" accent="maroon" />
    </div>

    <form method="GET" class="mb-4 flex flex-wrap gap-3">
        <div class="relative max-w-xs flex-1">
            <i class="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-xs text-ink/30"></i>
            <x-admin.input type="search" name="search" value="{{ request('search') }}" placeholder="Product name or SKU…" class="pl-9" />
        </div>
        <x-admin.select name="stock_status" class="max-w-[180px]" onchange="this.form.submit()">
            <option value="">All Stock Levels</option>
            <option value="low" @selected(request('stock_status') === 'low')>Low Stock</option>
            <option value="out" @selected(request('stock_status') === 'out')>Out of Stock</option>
        </x-admin.select>
        <x-admin.button variant="ghost">Filter</x-admin.button>
    </form>

    <div
        x-data="{
            open: false,
            variant: { id: null, quantity: 0, low_stock_threshold: 5, label: '' },
            openAdjust(v) { this.variant = v; this.open = true },
        }"
    >
        <x-admin.card :padded="false">
            @if ($variants->isEmpty())
                <x-admin.empty-state icon="fa-solid fa-boxes-stacked" title="No stock to show" subtitle="Add products with stock quantities to see them here." />
            @else
                <div class="overflow-x-auto">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Variant</th>
                                <th>SKU</th>
                                <th class="text-center">Available</th>
                                <th class="text-center">Threshold</th>
                                <th>Status</th>
                                <th class="text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($variants as $v)
                                @php
                                    $inv = $v->inventory;
                                    $statusColor = $inv->is_out_of_stock ? 'red' : ($inv->is_low_stock ? 'amber' : 'green');
                                    $statusLabel = $inv->is_out_of_stock ? 'Out of Stock' : ($inv->is_low_stock ? 'Low Stock' : 'In Stock');
                                    $variantLabel = $v->label ?? $v->sku;
                                    // The parent product can be soft-deleted (or, in theory, missing
                                    // entirely) while its variant/inventory rows are deliberately kept —
                                    // this must render, not crash, so stock on a delisted product can
                                    // still be reviewed/zeroed out from here.
                                    $productImage = $v->product?->primaryImage;
                                    $productName = $v->product?->name;
                                @endphp
                                <tr>
                                    <td>
                                        <div class="flex items-center gap-3">
                                            <div class="flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-black/5">
                                                @if ($productImage)
                                                    <img src="{{ Storage::url($productImage->image_path) }}" alt="" class="h-full w-full object-cover">
                                                @else
                                                    <i class="fa-solid fa-image text-xs text-ink/20" title="No Image Available"></i>
                                                @endif
                                            </div>
                                            @if ($productName)
                                                <span class="font-medium text-ink">{{ $productName }}</span>
                                            @else
                                                <span class="italic text-ink/40" title="This product has been removed from the catalog">Product Unavailable</span>
                                            @endif
                                        </div>
                                    </td>
                                    <td class="text-ink/60">
                                        @if ($v->color)
                                            <span class="mr-1.5 inline-block h-3 w-3 rounded-full align-middle" style="background-color: {{ $v->color->hex_code ?? '#e5e5e5' }}"></span>
                                        @endif
                                        {{ $variantLabel }}
                                    </td>
                                    <td class="font-mono text-xs text-ink/50">{{ $v->sku }}</td>
                                    <td class="text-center tabular-nums font-medium text-ink">{{ $inv->available_quantity }}</td>
                                    <td class="text-center tabular-nums text-ink/50">{{ $inv->low_stock_threshold }}</td>
                                    <td><x-admin.badge :color="$statusColor">{{ $statusLabel }}</x-admin.badge></td>
                                    <td>
                                        <div class="flex items-center justify-end gap-3">
                                            <button
                                                type="button"
                                                x-on:click="openAdjust(@js(['id' => $v->id, 'quantity' => $inv->quantity, 'low_stock_threshold' => $inv->low_stock_threshold, 'label' => ($productName ?? 'Product Unavailable').' — '.$variantLabel]))"
                                                class="text-ink/50 hover:text-ink" title="Adjust Stock"
                                            >
                                                <i class="fa-solid fa-pen"></i>
                                            </button>
                                            <a href="{{ route('admin.inventory.movements', $v) }}" class="text-ink/50 hover:text-ink" title="View History">
                                                <i class="fa-solid fa-clock-rotate-left"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                <div class="border-t border-black/5 px-5 py-4">
                    {{ $variants->links() }}
                </div>
            @endif
        </x-admin.card>

        {{-- Adjust Stock Modal --}}
        <div x-show="open" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4">
            <div x-show="open" x-transition.opacity x-on:click="open = false" class="absolute inset-0 bg-ink/50"></div>

            <div x-show="open" x-transition class="relative w-full max-w-sm rounded-xl bg-white p-6 shadow-2xl">
                <h3 class="mb-1 text-sm font-semibold text-ink">Adjust Stock</h3>
                <p class="mb-4 text-xs text-ink/40" x-text="variant.label"></p>

                <form method="POST" x-bind:action="'{{ url('admin/inventory') }}/' + variant.id + '/adjust'">
                    @csrf

                    <div class="space-y-4">
                        <div>
                            <x-admin.label value="New Quantity" required />
                            <x-admin.input type="number" min="0" name="quantity" x-model.number="variant.quantity" required />
                        </div>
                        <div>
                            <x-admin.label value="Low Stock Threshold" />
                            <x-admin.input type="number" min="0" name="low_stock_threshold" x-model.number="variant.low_stock_threshold" />
                        </div>
                        <div>
                            <x-admin.label value="Reason (optional)" />
                            <x-admin.input name="reason" placeholder="e.g. Restocked from supplier" />
                        </div>
                    </div>

                    <div class="mt-6 flex items-center gap-3">
                        <x-admin.button variant="accent">Save</x-admin.button>
                        <button type="button" x-on:click="open = false" class="text-sm text-ink/50 hover:text-ink">Cancel</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</x-layouts.admin>
