<x-admin-layout
    active="batches"
    :title="__('batches.title')"
    :crumbs="[
        ['label' => __('admin.shell.brand_sub')],
        ['label' => __('batches.crumb_parent')],
        ['label' => __('batches.title')],
    ]">

    @php
        $today = now()->startOfDay();
    @endphp

    <div class="page-wide">
        <div class="page-header mb-6">
            <div>
                <h1 class="page-title">{{ __('batches.title') }}</h1>
                <p class="page-sub">{{ __('batches.sub') }}</p>
            </div>
            <div class="flex items-center gap-2">
                <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" />
                        {{ __('batches.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.batches.export', array_merge(request()->query(), ['format' => 'csv'])) }}"
                           class="dropdown-item" @click="close()">
                            <span class="dropdown-item-label">{{ __('batches.actions.export_csv') }}</span>
                        </a>
                        <a href="{{ route('admin.inventory.batches.export', array_merge(request()->query(), ['format' => 'xlsx'])) }}"
                           class="dropdown-item" @click="close()">
                            <span class="dropdown-item-label">{{ __('batches.actions.export_xlsx') }}</span>
                        </a>
                    </div>
                </div>
            </div>
        </div>

        {{-- Status tabs — quick filters with live counts driven by the
             controller. Clicking a tab refreshes the page with the
             matching `?status=` value. --}}
        <div class="batches-tabs mb-4">
            @php
                $tabs = [
                    ''               => ['label' => __('batches.tabs.all'),           'count' => $counts['all']],
                    'live'           => ['label' => __('batches.tabs.live'),          'count' => $counts['live']],
                    'expiring_soon'  => ['label' => __('batches.tabs.expiring_soon'), 'count' => $counts['expiring_soon']],
                    'expired'        => ['label' => __('batches.tabs.expired'),       'count' => $counts['expired']],
                ];
            @endphp
            @foreach ($tabs as $key => $tab)
                <a href="{{ route('admin.inventory.batches.index', array_merge(request()->query(), ['status' => $key])) }}"
                   class="batches-tab {{ $filters['status'] === $key ? 'is-active' : '' }}">
                    <span>{{ $tab['label'] }}</span>
                    <span class="batches-tab-count tnum">{{ $tab['count'] }}</span>
                </a>
            @endforeach
        </div>

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

        <div class="card card-pad-0"
             x-data="dataTable({ rowsSelector: 'tbody > tr[data-dt-row]' })">
            <div class="dt-toolbar">
                <div class="dt-toolbar-title">{{ __('batches.list_title') }} (<span x-text="rowCount">{{ $batches->count() }}</span>)</div>
                <x-admin.dt-toolbar-actions />
            </div>

            <form method="GET" action="{{ route('admin.inventory.batches.index') }}" class="inv-filter">
                <input type="hidden" name="status" value="{{ $filters['status'] }}">
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('batches.columns.store') }}</span>
                    <select name="store_id" class="pos-input" x-data="enhancedSelect()" onchange="this.form.submit()">
                        <option value="">{{ __('batches.filter.store_all') }}</option>
                        @foreach ($stores as $store)
                            <option value="{{ $store->id }}" @selected($filters['storeId'] === $store->id)>{{ $store->name }}</option>
                        @endforeach
                    </select>
                </label>
                @if ($filters['status'] === 'expiring_soon')
                    <label class="field inv-filter-select">
                        <span class="field-label">{{ __('batches.filter.window') }}</span>
                        <select name="days" class="pos-input" x-data="enhancedSelect()" onchange="this.form.submit()">
                            @foreach ([7, 14, 30, 60, 90] as $d)
                                <option value="{{ $d }}" @selected($filters['days'] === $d)>{{ __('batches.filter.days', ['n' => $d]) }}</option>
                            @endforeach
                        </select>
                    </label>
                @endif
                <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="{{ $filters['q'] }}" class="pos-input"
                               placeholder="{{ __('batches.filter.search') }}">
                    </span>
                </label>
                <x-admin.filter-reset route="admin.inventory.batches.index" />
            </form>

            @if ($batches->isEmpty())
                <div class="dt-empty">
                    <span class="dt-empty-icon"><x-icon name="tag" class="w-5 h-5" /></span>
                    <div class="dt-empty-title">{{ __('batches.empty.title') }}</div>
                    <div class="dt-empty-sub">{{ __('batches.empty.sub') }}</div>
                </div>
            @else
                <div class="dt-scroll">
                <table class="dt-table">
                    <thead>
                        <tr>
                            <th>{{ __('batches.columns.product') }}</th>
                            <th>{{ __('batches.columns.store') }}</th>
                            <th>{{ __('batches.columns.batch') }}</th>
                            <th>{{ __('batches.columns.mfg') }}</th>
                            <th>{{ __('batches.columns.expiry') }}</th>
                            <th class="num">{{ __('batches.columns.on_hand') }}</th>
                            <th>{{ __('batches.columns.status') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($batches as $batch)
                            @php
                                $isExpired       = $batch->isExpired();
                                $isExpiringSoon  = $batch->isExpiringSoon(30);
                                $daysToExpiry    = $batch->expiry_date
                                    ? $today->diffInDays($batch->expiry_date->startOfDay(), false)
                                    : null;
                            @endphp
                            <tr class="prod-row" data-dt-row
                                data-dt-name="{{ $batch->batch_number . ' ' . ($batch->product?->name) }}">
                                <td>
                                    <div class="font-medium">{{ $batch->product?->name ?? '—' }}</div>
                                    <div class="fg-tertiary text-xs mono">
                                        {{ $batch->product?->sku ?? '—' }}
                                        @if ($batch->variant?->sku)
                                            · {{ $batch->variant->sku }}
                                        @endif
                                    </div>
                                </td>
                                <td>{{ $batch->store?->name ?? '—' }}</td>
                                <td class="mono">{{ $batch->batch_number }}</td>
                                <td>{{ $batch->manufacture_date?->toDateString() ?: '—' }}</td>
                                <td>
                                    @if ($batch->expiry_date)
                                        <span>{{ $batch->expiry_date->toDateString() }}</span>
                                        @if ($daysToExpiry !== null)
                                            <span class="fg-tertiary text-xs ms-1">
                                                @if ($daysToExpiry < 0)
                                                    {{ __('batches.expiry.expired_n_days', ['n' => abs($daysToExpiry)]) }}
                                                @elseif ($daysToExpiry === 0)
                                                    {{ __('batches.expiry.today') }}
                                                @else
                                                    {{ __('batches.expiry.in_n_days', ['n' => $daysToExpiry]) }}
                                                @endif
                                            </span>
                                        @endif
                                    @else
                                        <span class="fg-tertiary">—</span>
                                    @endif
                                </td>
                                <td class="num tnum">{{ rtrim(rtrim((string) $batch->quantity, '0'), '.') }}</td>
                                <td>
                                    @if ($isExpired)
                                        <span class="prod-badge prod-badge-danger">{{ __('batches.status.expired') }}</span>
                                    @elseif ($isExpiringSoon)
                                        <span class="prod-badge prod-badge-warning">{{ __('batches.status.expiring_soon') }}</span>
                                    @else
                                        <span class="prod-badge prod-badge-positive">{{ __('batches.status.live') }}</span>
                                    @endif
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
                </div>
                <x-admin.dt-pager />
            @endif
        </div>
    </div>
</x-admin-layout>
