<x-admin-layout
    active="stock-levels"
    :title="__('inventory.levels.title')"
    :crumbs="[
        ['label' => __('admin.shell.brand_sub')],
        ['label' => __('inventory.nav.section')],
        ['label' => __('inventory.levels.title')],
    ]">

    <div class="page-wide">
        <div class="page-header mb-6">
            <div>
                <h1 class="page-title">{{ __('inventory.levels.title') }}</h1>
                <p class="page-sub">{{ __('inventory.levels.sub') }}</p>
            </div>
            <div class="dropdown" x-data="dropdown">
                <button type="button"
                        class="pos-btn pos-btn-sm pos-btn-ghost"
                        @click="toggle()"
                        :aria-expanded="open">
                    <x-icon name="download" class="w-4 h-4" />
                    {{ __('inventory.levels.actions.export') }}
                    <x-icon name="chevron" class="w-4 h-4" />
                </button>
                <div class="dropdown-panel"
                     x-show="open"
                     x-cloak
                     @click.outside="close()"
                     @keydown.escape.window="close()">
                    <a href="{{ route('admin.inventory.levels.export', ['format' => 'csv']) }}"
                       class="dropdown-item"
                       @click="close()">
                        <span class="dropdown-item-label">{{ __('inventory.levels.actions.export_csv') }}</span>
                    </a>
                    <a href="{{ route('admin.inventory.levels.export', ['format' => 'xlsx']) }}"
                       class="dropdown-item"
                       @click="close()">
                        <span class="dropdown-item-label">{{ __('inventory.levels.actions.export_xlsx') }}</span>
                    </a>
                </div>
            </div>
        </div>

        <x-admin.summary-cards :cards="$summaryCards" />

        <div class="card card-pad-0"
             x-data="dataTable({ rowsSelector: 'tbody > tr[data-dt-row]' })">
            {{-- Server-side filter toolbar inside the same card as the
                 table — same chrome as `.dt-toolbar`, with room for
                 multiple labelled fields. Filtering narrows the row
                 set; pagination + free-text search run client-side via
                 the data-table mixin (same as Categories / Products). --}}
            <div class="dt-toolbar">
                <div class="dt-toolbar-title">{{ __('inventory.levels.list_title', ['count' => $levels->count()]) }}</div>
                <x-admin.dt-toolbar-actions />
            </div>
            <form method="GET" action="{{ route('admin.inventory.levels.index') }}" class="inv-filter">
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('inventory.levels.columns.store') }}</span>
                    <select name="store_id" class="pos-input" x-data="enhancedSelect()" onchange="this.form.submit()">
                        <option value="">{{ __('inventory.levels.filter.store_all') }}</option>
                        @foreach ($stores as $store)
                            <option value="{{ $store->id }}" @selected($storeId === $store->id)>{{ $store->name }}</option>
                        @endforeach
                    </select>
                </label>
                <label class="field inv-filter-search">
                    <span class="field-label">&nbsp;</span>
                    <span class="inv-search">
                        <span class="inv-search-icon"><x-icon name="search" class="w-4 h-4" /></span>
                        <input type="search" name="q" value="{{ $q }}" class="pos-input"
                               placeholder="{{ __('inventory.levels.filter.search') }}">
                    </span>
                </label>
                <x-admin.filter-reset route="admin.inventory.levels.index" />
            </form>

            @if ($levels->isEmpty())
                <div class="dt-empty">
                    <span class="dt-empty-icon"><x-icon name="box" class="w-5 h-5" /></span>
                    <div class="dt-empty-title">{{ __('inventory.levels.empty') }}</div>
                </div>
            @else
                <div class="dt-scroll">
                <table class="dt-table">
                    <thead>
                        <tr>
                            <th>{{ __('inventory.levels.columns.product') }}</th>
                            <th>{{ __('inventory.levels.columns.sku') }}</th>
                            <th>{{ __('inventory.levels.columns.store') }}</th>
                            <th class="num">{{ __('inventory.levels.columns.quantity') }}</th>
                            <th class="num">{{ __('inventory.levels.columns.reserved') }}</th>
                            <th class="num">{{ __('inventory.levels.columns.wac') }}</th>
                            <th class="num">{{ __('inventory.levels.columns.reorder') }}</th>
                            <th>{{ __('inventory.levels.columns.last_move') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($levels as $level)
                            @php
                                $product    = $level->product;
                                $variant    = $level->variant;
                                $qty        = (float) $level->quantity;
                                $reorder    = $level->reorder_level_override ?? $product?->reorder_level;
                                $isLow      = $reorder !== null && $qty <= (float) $reorder;
                                $isNegative = $qty < 0;
                            @endphp
                            <tr data-dt-row
                                data-dt-name="{{ $product?->name ?? '' }}"
                                data-dt-id="{{ $level->id }}">
                                <td>
                                    <div class="store-row-name-line">
                                        <span class="store-row-name">{{ $product?->name ?? '—' }}</span>
                                        @if ($variant) <span class="fg-tertiary">· {{ $variant->label }}</span> @endif
                                        @if ($isNegative)
                                            <span class="prod-badge prod-badge-danger">{{ __('inventory.levels.badges.negative') }}</span>
                                        @elseif ($isLow)
                                            <span class="prod-badge prod-badge-warning">{{ __('inventory.levels.badges.low') }}</span>
                                        @endif
                                    </div>
                                </td>
                                <td class="mono">{{ $variant?->sku ?? $product?->sku }}</td>
                                <td>{{ $level->store?->name }}</td>
                                <td class="num tnum">{{ rtrim(rtrim(number_format($qty, 4, '.', ''), '0'), '.') ?: '0' }}</td>
                                <td class="num tnum fg-tertiary">{{ rtrim(rtrim(number_format((float) $level->reserved_quantity, 4, '.', ''), '0'), '.') ?: '0' }}</td>
                                {{-- Weighted-average cost — updated automatically by every positive costed
                                     stock movement (purchase receipts, opening adjustments). Shown in 0
                                     when no costed receipt has ever landed. --}}
                                <td class="num tnum">{{ (float) $level->weighted_average_cost > 0 ? format_money($level->weighted_average_cost) : '—' }}</td>
                                <td class="num">
                                    <form method="POST" action="{{ route('admin.inventory.levels.reorder', $level) }}" class="inline-flex" data-ajax-form>
                                        @csrf
                                        @method('PATCH')
                                        <input type="number" name="reorder_level_override"
                                               value="{{ $level->reorder_level_override !== null ? rtrim(rtrim(number_format((float) $level->reorder_level_override, 4, '.', ''), '0'), '.') : '' }}"
                                               step="any" min="0"
                                               class="pos-input pos-input-sm inv-reorder-input tnum"
                                               placeholder="{{ $product?->reorder_level !== null ? number_format((float) $product->reorder_level, 0) : '—' }}"
                                               @change="$el.form.requestSubmit()">
                                    </form>
                                </td>
                                <td>{{ $level->last_movement_at?->diffForHumans() ?? '—' }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
                </div>

                <x-admin.dt-pager />
            @endif
        </div>
    </div>
</x-admin-layout>
