@extends('layouts.app')

@section('title', $asset->asset_tag)

@section('content')
    <x-page-header
        :title="$asset->asset_tag"
        :subtitle="$asset->name">
        <x-slot:breadcrumbs>
            <li class="breadcrumb-item"><a href="{{ route('assets.index') }}">Assets</a></li>
            <li class="breadcrumb-item active" aria-current="page">{{ $asset->asset_tag }}</li>
        </x-slot:breadcrumbs>

        <a href="{{ route('assets.edit', $asset) }}" class="btn btn-outline-secondary">
            <i class="bi bi-pencil" aria-hidden="true"></i>Edit
        </a>

        @if ($asset->current_assignment_id)
            <a href="{{ route('returns.create', ['assignment' => $asset->current_assignment_id]) }}" class="btn btn-primary">
                <i class="bi bi-box-arrow-in-left" aria-hidden="true"></i>Record Return
            </a>
        @elseif ($asset->status->canBeAssigned())
            <a href="{{ route('assignments.create', ['asset_id' => $asset->id]) }}" class="btn btn-primary">
                <i class="bi bi-box-arrow-right" aria-hidden="true"></i>Assign
            </a>
        @endif
    </x-page-header>

    <div class="row g-3">
        <div class="col-xl-8">
            <div class="d-flex flex-column gap-3">

                <x-panel title="Overview">
                    <div class="d-flex align-items-center gap-3 mb-3 pb-3 border-bottom">
                        <span class="ams-tile ams-tile--lg ams-tile--{{ $asset->category->is_active ? 'primary' : 'secondary' }}" aria-hidden="true">
                            <i class="bi bi-{{ $asset->status->icon() }}"></i>
                        </span>
                        <div class="min-width-0">
                            <div class="fw-semibold ams-truncate">{{ $asset->name }}</div>
                            <div class="ams-text-xs text-secondary ams-truncate">
                                {{ $asset->category->qualifiedName() }}
                                @if ($asset->manufacturer || $asset->model)
                                    · {{ trim(($asset->manufacturer ?? '').' '.($asset->model ?? '')) }}
                                @endif
                            </div>
                        </div>
                        <div class="ms-auto flex-shrink-0 d-flex gap-1">
                            <x-status-badge :status="$asset->status" />
                            <x-status-badge :status="$asset->condition" />
                        </div>
                    </div>

                    <x-detail-list>
                        <x-detail-row label="Asset Tag">
                            <span class="ams-cell-code">{{ $asset->asset_tag }}</span>
                        </x-detail-row>

                        <x-detail-row label="Serial Number">
                            @if ($asset->serial_number)
                                <span class="ams-mono">{{ $asset->serial_number }}</span>
                            @endif
                        </x-detail-row>

                        <x-detail-row label="MAC Address">
                            @if ($asset->mac_address)
                                <span class="ams-mono">{{ $asset->mac_address }}</span>
                            @endif
                        </x-detail-row>

                        <x-detail-row label="Category">
                            {{ $asset->category->qualifiedName() }}
                        </x-detail-row>

                        <x-detail-row label="Location">
                            {{ $asset->location?->name }}
                        </x-detail-row>

                        <x-detail-row label="Team">
                            {{ $asset->team?->name }}
                        </x-detail-row>

                        <x-detail-row label="Active">
                            @if ($asset->is_active)
                                <x-badge color="success" dot>Active</x-badge>
                            @else
                                <x-badge color="secondary" dot>Inactive</x-badge>
                            @endif
                        </x-detail-row>
                    </x-detail-list>
                </x-panel>

                <x-panel title="Technical Information">
                    @if ($asset->manufacturer || $asset->model || ! empty($asset->specifications))
                        <x-detail-list>
                            <x-detail-row label="Manufacturer">{{ $asset->manufacturer }}</x-detail-row>
                            <x-detail-row label="Model">{{ $asset->model }}</x-detail-row>

                            @foreach ($asset->specifications ?? [] as $specKey => $specValue)
                                <x-detail-row :label="$specKey">{{ $specValue }}</x-detail-row>
                            @endforeach
                        </x-detail-list>
                    @else
                        <p class="text-secondary mb-0">No technical specifications recorded.</p>
                    @endif
                </x-panel>

                <x-panel title="Purchase Information">
                    <x-detail-list>
                        <x-detail-row label="Vendor">{{ $asset->vendor }}</x-detail-row>

                        <x-detail-row label="Purchase Date">
                            {{ $asset->purchase_date?->format(setting('date_format', 'd M Y')) }}
                        </x-detail-row>

                        <x-detail-row label="Purchase Cost">
                            @if ($asset->purchase_cost !== null)
                                {{ $asset->currency }} {{ number_format((float) $asset->purchase_cost, 2) }}
                            @endif
                        </x-detail-row>

                        <x-detail-row label="Age">
                            @if (($months = $asset->ageInMonths()) !== null)
                                {{ trans_choice(':count month|:count months', $months, ['count' => $months]) }}
                            @endif
                        </x-detail-row>

                        <x-detail-row label="Invoice Number">
                            <span class="ams-mono">{{ $asset->invoice_number }}</span>
                        </x-detail-row>

                        <x-detail-row label="PO Number">
                            <span class="ams-mono">{{ $asset->po_number }}</span>
                        </x-detail-row>
                    </x-detail-list>
                </x-panel>

                <x-panel title="Assignment History" subtitle="Every custody period this asset has had.">
                    @if ($asset->assignments->isEmpty())
                        <p class="text-secondary mb-0">This asset has never been assigned.</p>
                    @else
                        <div class="ams-table-scroll ams-scroll-thin">
                            <table class="table table-sm align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th scope="col">Employee</th>
                                        <th scope="col">Assigned On</th>
                                        <th scope="col">Returned On</th>
                                        <th scope="col">Condition</th>
                                        <th scope="col">Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($asset->assignments as $assignment)
                                        <tr>
                                            <td>
                                                <a href="{{ route('assignments.show', $assignment) }}" class="text-decoration-none">
                                                    {{ $assignment->employee->fullName() }}
                                                </a>
                                            </td>
                                            <td class="ams-cell-secondary">
                                                {{ $assignment->assigned_at->format(setting('date_format', 'd M Y')) }}
                                            </td>
                                            <td class="ams-cell-secondary">
                                                {{ $assignment->returned_at?->format(setting('date_format', 'd M Y')) ?? '—' }}
                                            </td>
                                            <td class="ams-cell-secondary">
                                                {{ $assignment->condition_on_issue->label() }}
                                                @if ($assignment->condition_on_return)
                                                    → {{ $assignment->condition_on_return->label() }}
                                                @endif
                                            </td>
                                            <td>
                                                <x-status-badge :status="$assignment->status" />
                                                @if ($assignment->isOverdue())
                                                    <x-badge color="danger" dot>Overdue</x-badge>
                                                @endif
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </x-panel>

                <x-panel title="Warranty History" subtitle="Every coverage period this asset has had.">
                    <x-slot:actions>
                        <a href="{{ route('assets.warranties.create', $asset) }}" class="btn btn-sm btn-outline-secondary">
                            <i class="bi bi-plus-lg" aria-hidden="true"></i>Add Warranty
                        </a>
                    </x-slot:actions>

                    @if ($asset->warranties->isEmpty())
                        <p class="text-secondary mb-0">No warranty recorded for this asset yet.</p>
                    @else
                        <div class="ams-table-scroll ams-scroll-thin">
                            <table class="table table-sm align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th scope="col">Type</th>
                                        <th scope="col">Provider</th>
                                        <th scope="col">Coverage</th>
                                        <th scope="col">Status</th>
                                        <th scope="col" class="text-end">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($asset->warranties as $warranty)
                                        <tr>
                                            <td>
                                                {{ $warranty->type->label() }}
                                                @if ($warranty->is_primary)
                                                    <x-badge color="primary" dot>Current</x-badge>
                                                @endif
                                            </td>
                                            <td class="ams-cell-secondary">{{ $warranty->provider ?? '—' }}</td>
                                            <td class="ams-cell-secondary">
                                                {{ $warranty->start_date->format('d M Y') }} – {{ $warranty->end_date->format('d M Y') }}
                                            </td>
                                            <td>
                                                <x-status-badge :status="$warranty->status()" />
                                            </td>
                                            <td class="text-end text-nowrap">
                                                <x-table.actions>
                                                    <a href="{{ route('assets.warranties.edit', [$asset, $warranty]) }}"
                                                       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 {{ $warranty->type->label() }}</span>
                                                    </a>

                                                    @if ($warranty->hasDocument())
                                                        <a href="{{ route('assets.warranties.document', [$asset, $warranty]) }}"
                                                           class="btn btn-sm btn-icon"
                                                           data-bs-toggle="tooltip"
                                                           title="Download document">
                                                            <i class="bi bi-file-earmark-arrow-down" aria-hidden="true"></i>
                                                            <span class="visually-hidden">Download document for {{ $warranty->type->label() }}</span>
                                                        </a>
                                                    @endif

                                                    @can('delete', $warranty)
                                                        <form method="POST"
                                                              action="{{ route('assets.warranties.destroy', [$asset, $warranty]) }}"
                                                              data-ams-confirm="Delete this {{ $warranty->type->label() }} record? You can restore it afterwards from the deleted list."
                                                              data-ams-confirm-title="Delete warranty"
                                                              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 {{ $warranty->type->label() }}</span>
                                                            </button>
                                                        </form>
                                                    @endcan
                                                </x-table.actions>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @endif
                </x-panel>

                <x-panel title="Documents" subtitle="Invoices, purchase orders and any other paperwork on file for this asset.">
                    <form method="POST"
                          action="{{ route('assets.documents.store', $asset) }}"
                          enctype="multipart/form-data"
                          class="d-flex flex-wrap align-items-end gap-2 mb-3 pb-3 border-bottom"
                          novalidate>
                        @csrf

                        <div class="ams-field mb-0" style="min-width: 12rem;">
                            <label for="document_type" class="form-label">Document Type</label>
                            <select name="document_type" id="document_type" class="form-select">
                                @foreach (\App\Enums\AssetDocumentType::options() as $value => $label)
                                    <option value="{{ $value }}">{{ $label }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="ams-field mb-0 flex-grow-1" style="min-width: 14rem;">
                            <label for="document" class="form-label">File</label>
                            <input type="file" name="document" id="document" class="form-control" accept=".pdf,.jpg,.jpeg,.png" required>
                        </div>

                        <button type="submit" class="btn btn-outline-secondary">
                            <i class="bi bi-upload" aria-hidden="true"></i>Upload
                        </button>
                    </form>

                    @if ($asset->documents->isEmpty())
                        <x-table.empty-state
                            icon="file-earmark-text"
                            title="No documents on file"
                            message="Upload the invoice, PO or any other paperwork for this asset above." />
                    @else
                        <div class="d-flex flex-column gap-2">
                            @foreach ($asset->documents as $document)
                                <div class="d-flex align-items-center justify-content-between gap-3 p-2 border rounded">
                                    <div class="min-width-0">
                                        <div class="ams-cell-primary ams-truncate">
                                            {{ $document->original_filename }}
                                            <x-badge :color="$document->document_type->color()">{{ $document->document_type->label() }}</x-badge>
                                        </div>
                                        <div class="ams-text-xs text-secondary">
                                            {{ $document->humanFileSize() }}
                                            &bull; Uploaded by {{ $document->uploadedBy?->name ?? 'Unknown' }}
                                            &bull; {{ $document->created_at?->format(setting('date_format', 'd M Y')) }}
                                        </div>
                                    </div>

                                    <x-table.actions>
                                        <a href="{{ route('assets.documents.show', [$asset, $document]) }}"
                                           class="btn btn-sm btn-icon"
                                           target="_blank"
                                           rel="noopener"
                                           data-bs-toggle="tooltip"
                                           title="View">
                                            <i class="bi bi-eye" aria-hidden="true"></i>
                                            <span class="visually-hidden">View {{ $document->original_filename }}</span>
                                        </a>

                                        <a href="{{ route('assets.documents.download', [$asset, $document]) }}"
                                           class="btn btn-sm btn-icon"
                                           data-bs-toggle="tooltip"
                                           title="Download">
                                            <i class="bi bi-file-earmark-arrow-down" aria-hidden="true"></i>
                                            <span class="visually-hidden">Download {{ $document->original_filename }}</span>
                                        </a>

                                        @can('delete', $document)
                                            <form method="POST"
                                                  action="{{ route('assets.documents.destroy', [$asset, $document]) }}"
                                                  data-ams-confirm="Delete {{ $document->original_filename }}? This cannot be undone."
                                                  data-ams-confirm-title="Delete document"
                                                  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 {{ $document->original_filename }}</span>
                                                </button>
                                            </form>
                                        @endcan
                                    </x-table.actions>
                                </div>
                            @endforeach
                        </div>
                    @endif
                </x-panel>

                @if ($asset->notes)
                    <x-panel title="Notes">
                        <p class="mb-0" style="white-space: pre-line;">{{ $asset->notes }}</p>
                    </x-panel>
                @endif

                <x-panel title="Recent Activity">
                    <x-slot:actions>
                        <a href="{{ route('assets.history', $asset) }}" class="btn btn-sm btn-outline-secondary">
                            View Full History
                        </a>
                    </x-slot:actions>

                    @if ($recentActivity->isEmpty())
                        <p class="text-secondary mb-0">No activity recorded yet.</p>
                    @else
                        <ul class="ams-checklist">
                            @foreach ($recentActivity as $log)
                                <li class="is-done">
                                    <i class="bi bi-{{ $log->event->icon() }}" aria-hidden="true"></i>
                                    <span class="min-width-0">
                                        <span class="d-block ams-truncate">{{ $log->description }}</span>
                                        <span class="ams-text-xs text-body-tertiary">
                                            {{ $log->user?->name ?? 'System' }}
                                            ·
                                            {{ $log->created_at?->format(setting('datetime_format', 'd M Y, H:i')) }}
                                        </span>
                                    </span>
                                </li>
                            @endforeach
                        </ul>
                    @endif
                </x-panel>

            </div>
        </div>

        <div class="col-xl-4">
            <div class="d-flex flex-column gap-3">

                <x-panel title="Current Status">
                    <div class="d-flex align-items-center justify-content-between mb-3">
                        <x-status-badge :status="$asset->status" class="fs-6" />
                    </div>

                    @if ($asset->currentEmployee)
                        <x-detail-list class="mb-3 pb-3 border-bottom">
                            <x-detail-row label="Held By">
                                <a href="{{ route('employees.show', $asset->currentEmployee) }}">
                                    {{ $asset->currentEmployee->fullName() }}
                                </a>
                            </x-detail-row>

                            @if ($asset->currentAssignment)
                                <x-detail-row label="Since">
                                    {{ $asset->currentAssignment->assigned_at->format(setting('date_format', 'd M Y')) }}
                                </x-detail-row>

                                @if ($asset->currentAssignment->expected_return_at)
                                    <x-detail-row label="Expected Back">
                                        {{ $asset->currentAssignment->expected_return_at->format(setting('date_format', 'd M Y')) }}
                                    </x-detail-row>
                                @endif
                            @endif
                        </x-detail-list>
                    @endif

                    @php $transitions = $asset->status->allowedTransitions(); @endphp

                    @if (count($transitions) > 0)
                        <form method="POST" action="{{ route('assets.status', $asset) }}">
                            @csrf
                            @method('PATCH')

                            <x-form.select
                                name="status"
                                label="Change status to"
                                placeholder="Choose a new status"
                                :options="collect($transitions)->mapWithKeys(fn ($status) => [$status->value => $status->label()])->all()" />

                            <button type="submit" class="btn btn-sm btn-outline-secondary">
                                <i class="bi bi-arrow-repeat" aria-hidden="true"></i>Update Status
                            </button>
                        </form>
                    @else
                        <p class="ams-text-xs text-secondary mb-0">
                            {{ $asset->status->label() }} is a final state and cannot be changed further.
                        </p>
                    @endif
                </x-panel>

                <x-panel title="Warranty">
                    <x-slot:actions>
                        @if ($asset->primaryWarranty)
                            <a href="{{ route('assets.warranties.renew.create', [$asset, $asset->primaryWarranty]) }}" class="btn btn-sm btn-outline-secondary">
                                <i class="bi bi-arrow-repeat" aria-hidden="true"></i>Renew
                            </a>
                        @else
                            <a href="{{ route('assets.warranties.create', $asset) }}" class="btn btn-sm btn-outline-secondary">
                                <i class="bi bi-plus-lg" aria-hidden="true"></i>Add
                            </a>
                        @endif
                    </x-slot:actions>

                    @if ($asset->primaryWarranty)
                        @php $primary = $asset->primaryWarranty; @endphp
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <x-status-badge :status="$primary->status()" class="fs-6" />
                        </div>

                        <x-detail-list>
                            <x-detail-row label="Type">{{ $primary->type->label() }}</x-detail-row>
                            <x-detail-row label="Provider">{{ $primary->provider }}</x-detail-row>
                            <x-detail-row label="Covered To">{{ $primary->end_date->format(setting('date_format', 'd M Y')) }}</x-detail-row>
                        </x-detail-list>

                        <a href="{{ route('assets.warranties.edit', [$asset, $primary]) }}" class="btn btn-sm btn-outline-secondary w-100 mt-2">
                            <i class="bi bi-pencil" aria-hidden="true"></i>Edit Coverage
                        </a>
                    @else
                        <x-table.empty-state
                            icon="shield-check"
                            title="No warranty on file"
                            message="Add the manufacturer warranty, an AMC or an insurance policy for this asset." />
                    @endif
                </x-panel>

                <x-panel title="QR Code" subtitle="Scanning this code opens this page.">
                    <div class="text-center">
                        <img src="{{ route('assets.qr', $asset) }}"
                             alt="QR code for {{ $asset->asset_tag }}"
                             width="180"
                             height="180"
                             class="border rounded-3 p-2 mb-2">

                        <div class="ams-text-xs text-secondary text-break mb-3">
                            {{ route('assets.scan', ['uuid' => $asset->uuid]) }}
                        </div>

                        <div class="d-flex flex-wrap justify-content-center gap-2">
                            <a href="{{ route('assets.qr', $asset) }}"
                               download="{{ $asset->asset_tag }}-qr.svg"
                               class="btn btn-sm btn-outline-secondary">
                                <i class="bi bi-download" aria-hidden="true"></i>SVG
                            </a>

                            <a href="{{ route('assets.qr.png', $asset) }}"
                               download="{{ $asset->asset_tag }}-qr.png"
                               class="btn btn-sm btn-outline-secondary">
                                <i class="bi bi-download" aria-hidden="true"></i>PNG
                            </a>

                            <a href="{{ route('assets.qr.print', $asset) }}"
                               class="btn btn-sm btn-outline-secondary">
                                <i class="bi bi-printer" aria-hidden="true"></i>Print Label
                            </a>
                        </div>
                    </div>
                </x-panel>

                <x-panel title="Record">
                    <x-detail-list>
                        <x-detail-row label="Added by">{{ $asset->creator?->name ?? 'Unknown' }}</x-detail-row>
                        <x-detail-row label="Added on">
                            {{ $asset->created_at?->format(setting('datetime_format', 'd M Y, H:i')) }}
                        </x-detail-row>
                        <x-detail-row label="Last updated by">{{ $asset->updater?->name ?? 'Unknown' }}</x-detail-row>
                        <x-detail-row label="Last updated on">
                            {{ $asset->updated_at?->format(setting('datetime_format', 'd M Y, H:i')) }}
                        </x-detail-row>
                    </x-detail-list>
                </x-panel>

                @can('delete', $asset)
                    <x-panel
                        title="Delete asset"
                        subtitle="Kept on record and restorable from the deleted list."
                        tone="danger">

                        <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-outline-danger">
                                <i class="bi bi-trash3" aria-hidden="true"></i>Delete Asset
                            </button>
                        </form>
                    </x-panel>
                @endcan

            </div>
        </div>
    </div>
@endsection
