@extends('layouts.app')
@section('title', $asset->code)
@section('content')
<div class="flex items-center gap-3 mb-6">
    <a href="{{ route('assets.index') }}" class="text-gray-400 hover:text-gray-600">
        <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
        </svg>
    </a>
    <div class="flex items-center gap-3">
        <span class="text-lg font-mono font-bold text-blue-600">{{ $asset->code }}</span>
        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium {{ $asset->status_color }}">
            {{ $asset->status_label }}
        </span>
        @if($asset->isWarrantyExpired())
        <span class="text-sm text-red-500 font-medium">⚠ Garantía vencida</span>
        @elseif($asset->isWarrantyExpiringSoon())
        <span class="text-sm text-yellow-500 font-medium">⏰ Garantía por vencer</span>
        @endif
    </div>
    @can('assets.edit')
    <a href="{{ route('assets.edit', $asset) }}"
       class="ml-auto px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 transition">
        Editar
    </a>
    @endcan
</div>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

    {{-- Columna principal --}}
    <div class="lg:col-span-2 space-y-5">

        {{-- Info del activo --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <h2 class="text-xl font-bold text-gray-900 mb-4">{{ $asset->name }}</h2>
            <dl class="grid grid-cols-2 gap-4">
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Categoría</dt>
                    <dd class="text-sm text-gray-900 mt-1 flex items-center gap-2">
                        <div class="h-2.5 w-2.5 rounded-full" style="background-color: {{ $asset->category->color }}"></div>
                        {{ $asset->category->name }}
                    </dd>
                </div>
                @if($asset->model)
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Modelo</dt>
                    <dd class="text-sm text-gray-900 mt-1">
                        {{ $asset->model->manufacturer?->name }} {{ $asset->model->name }}
                    </dd>
                </div>
                @endif
                @if($asset->serial_number)
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Número de serie</dt>
                    <dd class="text-sm font-mono text-gray-900 mt-1">{{ $asset->serial_number }}</dd>
                </div>
                @endif
                @if($asset->location)
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Ubicación</dt>
                    <dd class="text-sm text-gray-900 mt-1">{{ $asset->location }}</dd>
                </div>
                @endif
                @if($asset->purchase_date)
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Fecha compra</dt>
                    <dd class="text-sm text-gray-900 mt-1">{{ $asset->purchase_date->format('d/m/Y') }}</dd>
                </div>
                @endif
                @if($asset->purchase_price)
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Valor</dt>
                    <dd class="text-sm text-gray-900 mt-1">$ {{ number_format($asset->purchase_price, 0, ',', '.') }}</dd>
                </div>
                @endif
                @if($asset->warranty_until)
                <div>
                    <dt class="text-xs text-gray-500 uppercase tracking-wide">Garantía hasta</dt>
                    <dd class="text-sm mt-1 {{ $asset->isWarrantyExpired() ? 'text-red-500' : 'text-gray-900' }}">
                        {{ $asset->warranty_until->format('d/m/Y') }}
                    </dd>
                </div>
                @endif
            </dl>

            {{-- Campos personalizados --}}
            @if($asset->category->customFields->count() > 0)
            <div class="mt-5 pt-4 border-t border-gray-100">
                <h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">
                    Características técnicas
                </h4>
                <dl class="grid grid-cols-2 gap-3">
                    @foreach($asset->category->customFields as $field)
                    @php $val = $asset->getFieldValue($field->id) @endphp
                    <div>
                        <dt class="text-xs text-gray-500">{{ $field->label }}</dt>
                        <dd class="text-sm text-gray-900 mt-0.5">{{ $val ?? '—' }}</dd>
                    </div>
                    @endforeach
                </dl>
            </div>
            @endif

            @if($asset->notes)
            <div class="mt-4 pt-4 border-t border-gray-100">
                <p class="text-xs text-gray-500 uppercase tracking-wide mb-1">Notas</p>
                <p class="text-sm text-gray-700">{{ $asset->notes }}</p>
            </div>
            @endif
        </div>

        {{-- Bitácora de intervenciones --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                <h3 class="text-sm font-semibold text-gray-900">
                    Bitácora de Intervenciones ({{ $asset->interventions->count() }})
                </h3>
            </div>

            {{-- Formulario nueva intervención --}}
            @can('assets.edit')
            <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
                <p class="text-xs font-semibold text-gray-500 uppercase mb-3">Registrar intervención</p>
                <form method="POST" action="{{ route('assets.intervention', $asset) }}">
                    @csrf
                    <div class="grid grid-cols-2 gap-3 mb-3">
                        <select name="type" class="rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500" required>
                            @foreach(\App\Models\AssetIntervention::$types as $key => $label)
                            <option value="{{ $key }}">{{ $label }}</option>
                            @endforeach
                        </select>
                        <input type="date" name="intervention_date" value="{{ date('Y-m-d') }}"
                               class="rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500" required>
                        <input type="text" name="title" placeholder="Título de la intervención"
                               class="col-span-2 rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500" required>
                        <textarea name="description" rows="2" placeholder="Descripción detallada..."
                                  class="col-span-2 rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500" required></textarea>
                        <div>
                            <label class="text-xs text-gray-500 mb-1 block">Costo (opcional)</label>
                            <input type="number" name="cost" step="0.01" placeholder="0.00"
                                   class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label class="text-xs text-gray-500 mb-1 block">Estado resultante</label>
                            <select name="status_after" class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                                <option value="">— Sin cambio —</option>
                                @foreach(\App\Models\Asset::$statuses as $key => $s)
                                <option value="{{ $key }}">{{ $s['label'] }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <button type="submit"
                            class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition">
                        Registrar
                    </button>
                </form>
            </div>
            @endcan

            <div class="divide-y divide-gray-100">
                @forelse($asset->interventions as $intervention)
                <div class="px-6 py-4">
                    <div class="flex items-center justify-between mb-1">
                        <div class="flex items-center gap-2">
                            <span class="text-xs font-medium px-2 py-0.5 rounded-full
                                {{ $intervention->type === 'repair' ? 'bg-red-100 text-red-700' :
                                   ($intervention->type === 'maintenance' ? 'bg-blue-100 text-blue-700' :
                                   ($intervention->type === 'upgrade' ? 'bg-purple-100 text-purple-700' : 'bg-gray-100 text-gray-700')) }}">
                                {{ $intervention->type_label }}
                            </span>
                            <span class="text-sm font-medium text-gray-900">{{ $intervention->title }}</span>
                        </div>
                        <span class="text-xs text-gray-400">{{ $intervention->intervention_date->format('d/m/Y') }}</span>
                    </div>
                    <p class="text-sm text-gray-600 mt-1">{{ $intervention->description }}</p>
                    <div class="flex items-center gap-4 mt-2 text-xs text-gray-400">
                        <span>Técnico: {{ $intervention->technician->name }}</span>
                        @if($intervention->cost)
                        <span>Costo: ${{ number_format($intervention->cost, 0, ',', '.') }}</span>
                        @endif
                        @if($intervention->status_before && $intervention->status_after)
                        <span>{{ $intervention->status_before }} → {{ $intervention->status_after }}</span>
                        @endif
                    </div>
                </div>
                @empty
                <div class="px-6 py-8 text-center text-gray-400 text-sm">Sin intervenciones registradas.</div>
                @endforelse
            </div>
        </div>

        {{-- Historial de asignaciones --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-900">Historial de Asignaciones</h3>
            </div>
            <div class="divide-y divide-gray-100">
                @forelse($asset->assignments as $assignment)
                <div class="px-6 py-3 flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <img src="{{ $assignment->user->avatar_url }}" class="h-7 w-7 rounded-full">
                        <div>
                            <p class="text-sm font-medium text-gray-900">{{ $assignment->user->name }}</p>
                            <p class="text-xs text-gray-400">
                                Desde {{ $assignment->assigned_at->format('d/m/Y') }}
                                @if($assignment->returned_at)
                                    hasta {{ $assignment->returned_at->format('d/m/Y') }}
                                @else
                                    <span class="text-green-600 font-medium">— Actual</span>
                                @endif
                            </p>
                        </div>
                    </div>
                    @if($assignment->reason)
                    <span class="text-xs text-gray-400">{{ $assignment->reason }}</span>
                    @endif
                </div>
                @empty
                <div class="px-6 py-8 text-center text-gray-400 text-sm">Sin asignaciones registradas.</div>
                @endforelse
            </div>
        </div>

        {{-- Tickets relacionados --}}
        @if($asset->tickets->count() > 0)
        <div class="bg-white rounded-xl shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-900">
                    Tickets relacionados ({{ $asset->tickets->count() }})
                </h3>
            </div>
            <div class="divide-y divide-gray-100">
                @foreach($asset->tickets as $ticket)
                <a href="{{ route('tickets.show', $ticket) }}"
                   class="px-6 py-3 flex items-center justify-between hover:bg-gray-50 transition">
                    <div class="flex items-center gap-3">
                        <span class="text-sm font-mono text-blue-600">{{ $ticket->number }}</span>
                        <span class="text-sm text-gray-700">{{ $ticket->title }}</span>
                    </div>
                    <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium"
                          style="background-color: {{ $ticket->status->color }}20; color: {{ $ticket->status->color }}">
                        {{ $ticket->status->name }}
                    </span>
                </a>
                @endforeach
            </div>
        </div>
        @endif
    </div>

    {{-- Panel lateral --}}
    <div class="space-y-5">

        {{-- Usuario asignado --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <h3 class="text-sm font-semibold text-gray-900 mb-3">Usuario Asignado</h3>
            @if($asset->assignedUser)
            <div class="flex items-center gap-3">
                <img src="{{ $asset->assignedUser->avatar_url }}" class="h-10 w-10 rounded-full">
                <div>
                    <p class="text-sm font-medium text-gray-900">{{ $asset->assignedUser->name }}</p>
                    <p class="text-xs text-gray-500">{{ $asset->assignedUser->position ?? $asset->assignedUser->getRoleNames()->first() }}</p>
                </div>
            </div>
            @else
            <p class="text-sm text-gray-400">Sin asignar</p>
            @endif
        </div>

        {{-- Resumen --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <h3 class="text-sm font-semibold text-gray-900 mb-4">Resumen</h3>
            <dl class="space-y-3">
                <div class="flex justify-between">
                    <dt class="text-xs text-gray-500">Código</dt>
                    <dd class="text-xs font-mono font-semibold text-blue-600">{{ $asset->code }}</dd>
                </div>
                <div class="flex justify-between">
                    <dt class="text-xs text-gray-500">Intervenciones</dt>
                    <dd class="text-xs font-semibold text-gray-900">{{ $asset->interventions->count() }}</dd>
                </div>
                <div class="flex justify-between">
                    <dt class="text-xs text-gray-500">Tickets</dt>
                    <dd class="text-xs font-semibold text-gray-900">{{ $asset->tickets->count() }}</dd>
                </div>
                @if($asset->department)
                <div class="flex justify-between">
                    <dt class="text-xs text-gray-500">Departamento</dt>
                    <dd class="text-xs text-gray-900">{{ $asset->department->name }}</dd>
                </div>
                @endif
                <div class="flex justify-between">
                    <dt class="text-xs text-gray-500">Registrado</dt>
                    <dd class="text-xs text-gray-900">{{ $asset->created_at->format('d/m/Y') }}</dd>
                </div>
            </dl>
        </div>

        {{-- Acciones rápidas --}}
        @can('assets.edit')
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <h3 class="text-sm font-semibold text-gray-900 mb-3">Acciones</h3>
            <div class="space-y-2">
                <a href="{{ route('assets.edit', $asset) }}"
                   class="block w-full py-2 px-3 bg-blue-50 text-blue-700 text-sm font-medium rounded-lg hover:bg-blue-100 transition text-center">
                    Editar activo
                </a>
                @can('assets.delete')
                <form method="POST" action="{{ route('assets.destroy', $asset) }}"
                      onsubmit="return confirm('¿Dar de baja el activo {{ $asset->code }}?')">
                    @csrf @method('DELETE')
                    <button type="submit"
                            class="w-full py-2 px-3 bg-red-50 text-red-700 text-sm font-medium rounded-lg hover:bg-red-100 transition">
                        Dar de baja
                    </button>
                </form>
                @endcan
            </div>
        </div>
        @endcan
    </div>
</div>
@endsection
