@extends('layouts.app')

@section('title', $showingDeleted ? 'Deleted Assets' : 'Assets')

@section('content')
    @php
        $indexUrl = route('assets.index');
        $listUrl = $showingDeleted ? route('assets.index', ['trashed' => 1]) : $indexUrl;
        $hasFilters = (bool) array_filter($filters);
    @endphp

    <x-page-header
        :title="$showingDeleted ? 'Deleted Assets' : 'Assets'"
        :subtitle="trans_choice(':count asset|:count assets', $assets->total(), ['count' => $assets->total()])">

        @if ($showingDeleted)
            <a href="{{ $indexUrl }}" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left" aria-hidden="true"></i>Back to Assets
            </a>
        @else
            @if ($deletedCount > 0 && auth()->user()->is_master)
                <a href="{{ route('assets.index', ['trashed' => 1]) }}" class="btn btn-outline-secondary">
                    <i class="bi bi-trash3" aria-hidden="true"></i>Deleted
                    <x-badge color="secondary">{{ $deletedCount }}</x-badge>
                </a>
            @endif

            <a href="{{ route('assets.export', request()->query()) }}" class="btn btn-outline-secondary">
                <i class="bi bi-download" aria-hidden="true"></i>Export
            </a>

            <a href="{{ route('assets.create') }}" class="btn btn-primary">
                <i class="bi bi-plus-lg" aria-hidden="true"></i>Add Asset
            </a>
        @endif
    </x-page-header>

    {{--
        An empty form the bulk checkboxes and the bulk action bar's buttons
        point at via form="asset-bulk-form", even though neither is physically
        nested inside it — HTML forbids a <form> inside a <form>, and the table
        already has one form per row for its own Edit/Delete controls. The
        Export Selected button overrides this form's method and action per
        button via formmethod/formaction, so one shared field set can submit to
        either destination.
    --}}
    <form id="asset-bulk-form" method="POST" action="{{ route('assets.bulk-destroy') }}" class="d-none">
        @csrf
    </form>

    @unless ($showingDeleted)
        {{--
            Plain Bootstrap flex utilities rather than .ams-toolbar here: that
            class's spacer is tuned for the filter bar's fixed set of controls,
            and on a narrow screen it left this row's two buttons wrapping onto
            separate lines instead of staying paired.
        --}}
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2">
            <span class="fw-semibold ams-numeric">
                <span data-bulk-count>0</span> selected
            </span>

            <div class="d-flex flex-wrap gap-2">
                <button type="submit"
                        form="asset-bulk-form"
                        formaction="{{ route('assets.export') }}"
                        formmethod="GET"
                        class="btn btn-sm btn-outline-secondary">
                    <i class="bi bi-download" aria-hidden="true"></i>Export Selected
                </button>

                @if (auth()->user()->is_master)
                    <button type="submit"
                            form="asset-bulk-form"
                            class="btn btn-sm btn-outline-danger"
                            data-ams-confirm="Delete the selected assets? You can restore them afterwards from the deleted list."
                            data-ams-confirm-title="Delete selected assets"
                            data-ams-confirm-action="Delete">
                    <i class="bi bi-trash3" aria-hidden="true"></i>Delete Selected
                    </button>
                @endif
            </div>
        </div>
    @endunless

    <x-table.wrapper>
        <x-slot:toolbar>
            <x-filter-bar
                :action="$listUrl"
                :active="$hasFilters"
                :reset-url="$listUrl">

                @if ($showingDeleted)
                    <input type="hidden" name="trashed" value="1">
                @endif

                <x-filter.search :value="$filters['search']" placeholder="Search tag, name, serial, MAC, manufacturer…" />

                <x-filter.select
                    name="status"
                    label="Status"
                    placeholder="Any status"
                    :selected="$filters['status']"
                    :options="\App\Enums\AssetStatus::options()" />

                <x-filter.select
                    name="condition"
                    label="Condition"
                    placeholder="Any condition"
                    :selected="$filters['condition']"
                    :options="\App\Enums\AssetCondition::options()" />

                <x-filter.select
                    name="category_id"
                    label="Category"
                    placeholder="Any category"
                    :selected="$filters['category_id']"
                    :options="$categories->mapWithKeys(fn ($category) => [$category->id => $category->qualifiedName()])->all()" />

                <x-filter.select
                    name="location_id"
                    label="Location"
                    placeholder="Any location"
                    :selected="$filters['location_id']"
                    :options="$locations->pluck('name', 'id')->all()" />

                <x-filter.select
                    name="team_id"
                    label="Team"
                    placeholder="Any team"
                    :selected="$filters['team_id']"
                    :options="$teams->pluck('name', 'id')->all()" />
            </x-filter-bar>
        </x-slot:toolbar>

        <x-slot:head>
            <tr>
                @unless ($showingDeleted)
                    <th scope="col" style="width: 2.5rem;">
                        <input type="checkbox" class="form-check-input" data-bulk-select-all aria-label="Select all assets">
                    </th>
                @endunless
                <th scope="col">Asset</th>
                <th scope="col">Category</th>
                <th scope="col">Location</th>
                <th scope="col">Team</th>
                <th scope="col">Status</th>
                <th scope="col" class="text-end">Actions</th>
            </tr>
        </x-slot:head>

        @forelse ($assets as $asset)
            <tr>
                @unless ($showingDeleted)
                    <td>
                        <input type="checkbox"
                               class="form-check-input"
                               name="asset_ids[]"
                               value="{{ $asset->id }}"
                               form="asset-bulk-form"
                               data-bulk-select-item
                               aria-label="Select {{ $asset->asset_tag }}">
                    </td>
                @endunless

                <td>
                    <a href="{{ route('assets.show', $asset) }}" class="text-decoration-none">
                        <div class="ams-cell-code fw-semibold">{{ $asset->asset_tag }}</div>
                        <div class="ams-cell-secondary ams-truncate">{{ $asset->name }}</div>
                    </a>
                </td>

                <td class="ams-cell-secondary">{{ $asset->category->qualifiedName() }}</td>
                <td class="ams-cell-secondary">{{ $asset->location?->name ?? '—' }}</td>
                <td class="ams-cell-secondary">{{ $asset->team?->name ?? '—' }}</td>

                <td>
                    <x-status-badge :status="$asset->status" />
                    @if ($asset->currentEmployee)
                        <div class="ams-text-xs text-secondary ams-truncate mt-1">
                            <a href="{{ route('employees.show', $asset->currentEmployee) }}" class="text-decoration-none">
                                {{ $asset->currentEmployee->fullName() }}
                            </a>
                        </div>
                    @endif
                </td>

                <td class="text-end text-nowrap">
                    <x-table.actions>
                        @if ($showingDeleted)
                            @if (auth()->user()->is_master)
                                <form method="POST"
                                      action="{{ route('assets.restore', $asset) }}"
                                      data-ams-confirm="Restore {{ $asset->asset_tag }}?"
                                      data-ams-confirm-title="Restore asset"
                                      data-ams-confirm-action="Restore">
                                    @csrf
                                    @method('PATCH')
                                    <button type="submit" class="btn btn-sm btn-outline-success">
                                        <i class="bi bi-arrow-counterclockwise" aria-hidden="true"></i>Restore
                                    </button>
                                </form>
                            @endif
                        @else
                            <a href="{{ route('assets.show', $asset) }}"
                               class="btn btn-sm btn-icon"
                               data-bs-toggle="tooltip"
                               title="View">
                                <i class="bi bi-eye" aria-hidden="true"></i>
                                <span class="visually-hidden">View {{ $asset->asset_tag }}</span>
                            </a>

                            <a href="{{ route('assets.edit', $asset) }}"
                               class="btn btn-sm btn-icon"
                               data-bs-toggle="tooltip"
                               title="Edit">
                                <i class="bi bi-pencil" aria-hidden="true"></i>
                                <span class="visually-hidden">Edit {{ $asset->asset_tag }}</span>
                            </a>

                            @can('delete', $asset)
                                <form method="POST"
                                      action="{{ route('assets.destroy', $asset) }}"
                                      data-ams-confirm="Delete {{ $asset->asset_tag }}? You can restore it afterwards from the deleted list."
                                      data-ams-confirm-title="Delete asset"
                                      data-ams-confirm-action="Delete">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit"
                                            class="btn btn-sm btn-icon btn-outline-danger"
                                            data-bs-toggle="tooltip"
                                            title="Delete">
                                        <i class="bi bi-trash3" aria-hidden="true"></i>
                                        <span class="visually-hidden">Delete {{ $asset->asset_tag }}</span>
                                    </button>
                                </form>
                            @endcan
                        @endif
                    </x-table.actions>
                </td>
            </tr>
        @empty
            <tr>
                <td colspan="7" class="p-0">
                    <x-table.empty-state
                        icon="box-seam"
                        :title="$showingDeleted ? 'Nothing in the deleted list' : 'No assets match these filters'"
                        :message="$hasFilters
                            ? 'Try clearing the filters to see every asset.'
                            : ($showingDeleted
                                ? 'Deleted assets appear here and can be restored.'
                                : 'Add the first asset to start building the register.')">
                        @if ($hasFilters)
                            <a href="{{ $listUrl }}" class="btn btn-outline-secondary">
                                <i class="bi bi-x-lg" aria-hidden="true"></i>Clear filters
                            </a>
                        @elseif (! $showingDeleted)
                            <a href="{{ route('assets.create') }}" class="btn btn-primary">
                                <i class="bi bi-plus-lg" aria-hidden="true"></i>Add Asset
                            </a>
                        @endif
                    </x-table.empty-state>
                </td>
            </tr>
        @endforelse

        @if ($assets->hasPages())
            <x-slot:footer>
                <x-table.count :paginator="$assets" noun="asset" />
                {{ $assets->links() }}
            </x-slot:footer>
        @endif
    </x-table.wrapper>
@endsection
