@extends('layouts.app')

@section('title', $inventory->name . ' — TI Manager')

@section('content')
<div class="animate-fadeIn">
    {{-- Encabezado --}}
    <div class="page-header">
        <div class="page-header-top" style="flex-wrap: wrap; gap: 15px;">
            <div class="d-flex align-center gap-md" style="flex-wrap: wrap;">
                <a href="{{ route('inventory.index') }}" class="btn btn-ghost btn-icon" title="Volver al inventario">
                    <i class="ph ph-arrow-left"></i>
                </a>
                <div>
                    <h1 class="page-title" style="margin-bottom: 2px;">{{ $inventory->name }}</h1>
                    <span class="badge badge-{{ $inventory->status_color }}">{{ $inventory->status_label }}</span>
                </div>
            </div>
            @if(Auth::user()->canAccessCompany($inventory->branch->company_id))
                <div class="d-flex gap-sm" style="flex-wrap: wrap; align-items: center;">
                    <form id="form-device-report" method="POST" action="{{ route('reports.inventory.device-pdf', $inventory->id) }}" target="_blank" style="display: none;">
                        @csrf
                    </form>
                    @if(Auth::user()->isAdmin() || Auth::user()->isTechnician())
                        <button type="button" class="btn btn-outline btn-sm" onclick="openSignatureModal()">
                            <i class="ph ph-file-pdf"></i> Exportar PDF
                        </button>
                    @endif
                    <a href="{{ route('inventory.edit', $inventory) }}" class="btn btn-outline btn-sm">
                        <i class="ph ph-pencil"></i> Editar
                    </a>
                    <form method="POST" action="{{ route('inventory.destroy', $inventory) }}"
                          onsubmit="return confirm('¿Estás seguro de eliminar este equipo? Esta acción no se puede deshacer.');" style="margin: 0;">
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="btn btn-danger btn-sm">
                            <i class="ph ph-trash"></i> Eliminar
                        </button>
                    </form>
                </div>
            @endif
        </div>
    </div>

    <style>
        .masonry-grid {
            column-count: 1;
            column-gap: var(--space-lg);
        }
        @media (min-width: 768px) {
            .masonry-grid {
                column-count: 2;
            }
        }
        @media (min-width: 1200px) {
            .masonry-grid {
                column-count: 3;
            }
        }
        .masonry-grid > .card {
            break-inside: avoid;
            page-break-inside: avoid;
            margin-bottom: var(--space-lg);
            display: inline-block;
            width: 100%;
        }
    </style>
    <div class="masonry-grid">

        {{-- Card: Equipo --}}
        <div class="card">
            <div class="info-group">
                <div class="info-group-title">
                    <i class="ph ph-desktop-tower"></i> Equipo
                </div>
                <div class="info-row">
                    <span class="info-label">Nombre</span>
                    <span class="info-value">{{ $inventory->name }}</span>
                </div>
                @if($inventory->category)
                    <div class="info-row">
                        <span class="info-label">Categoría</span>
                        <span class="info-value">
                            <span class="d-flex align-center gap-xs" style="justify-content: flex-end;">
                                <i class="ph {{ $inventory->category->icon ?? 'ph-package' }}" style="color: var(--secondary);"></i>
                                {{ $inventory->category->name }}
                            </span>
                        </span>
                    </div>
                @endif
                @if($inventory->brand)
                    <div class="info-row">
                        <span class="info-label">Marca</span>
                        <span class="info-value">{{ $inventory->brand }}</span>
                    </div>
                @endif
                @if($inventory->model)
                    <div class="info-row">
                        <span class="info-label">Modelo</span>
                        <span class="info-value">{{ $inventory->model }}</span>
                    </div>
                @endif
            </div>
        </div>

        {{-- Card: Identificación --}}
        <div class="card">
            <div class="info-group">
                <div class="info-group-title">
                    <i class="ph ph-barcode"></i> Identificación
                </div>
                <div class="info-row">
                    <span class="info-label">Serial</span>
                    <span class="info-value" style="font-family: monospace;">{{ $inventory->serial_number ?? '—' }}</span>
                </div>
                <div class="info-row">
                    <span class="info-label">Etiqueta de activo</span>
                    <span class="info-value">{{ $inventory->asset_tag ?? '—' }}</span>
                </div>
                <div class="info-row">
                    <span class="info-label">Estado</span>
                    <span class="info-value">
                        <span class="badge badge-{{ $inventory->status_color }}">{{ $inventory->status_label }}</span>
                    </span>
                </div>
            </div>
        </div>

        {{-- Card: Ubicación --}}
        <div class="card">
            <div class="info-group">
                <div class="info-group-title">
                    <i class="ph ph-map-pin"></i> Ubicación
                </div>
                @if($inventory->branch && $inventory->branch->company)
                    <div class="info-row">
                        <span class="info-label">Empresa</span>
                        <span class="info-value">
                            <a href="{{ route('companies.show', $inventory->branch->company) }}" style="color: var(--secondary);">
                                {{ $inventory->branch->company->name }}
                            </a>
                        </span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Sede</span>
                        <span class="info-value">
                            <a href="{{ route('companies.branches.show', [$inventory->branch->company, $inventory->branch]) }}" style="color: var(--secondary);">
                                {{ $inventory->branch->name }}
                            </a>
                            @if($inventory->branch->is_main)
                                <span class="badge badge-primary" style="margin-left: 4px;">Principal</span>
                            @endif
                        </span>
                    </div>
                @endif
            </div>

            @if($inventory->branch && $inventory->branch->hasGps())
                <div style="margin-top: var(--space-md);">
                    <a href="{{ $inventory->branch->google_maps_url }}" target="_blank" class="btn btn-outline btn-sm" style="width: 100%;">
                        <i class="ph ph-navigation-arrow" style="color: var(--primary);"></i>
                        Ver sede en Google Maps
                    </a>
                </div>
            @endif
        </div>

        {{-- Card: Asignación --}}
        <div class="card">
            <div class="info-group">
                <div class="info-group-title">
                    <i class="ph ph-user"></i> Asignación
                </div>
                <div class="info-row">
                    <span class="info-label">Asignado a</span>
                    <span class="info-value">
                        @if($inventory->assigned_to)
                            <span class="d-flex align-center gap-xs" style="justify-content: flex-end;">
                                <i class="ph ph-user" style="color: var(--secondary);"></i>
                                {{ $inventory->assigned_to }}
                            </span>
                        @else
                            <span class="text-muted">Sin asignar</span>
                        @endif
                    </span>
                </div>
                <div class="info-row">
                    <span class="info-label">Dirección IP</span>
                    <span class="info-value" style="font-family: monospace;">{{ $inventory->ip_address ?? '—' }}</span>
                </div>
                <div class="info-row">
                    <span class="info-label">MAC Address</span>
                    <span class="info-value" style="font-family: monospace;">{{ $inventory->mac_address ?? '—' }}</span>
                </div>
                @if($inventory->parent_id && $inventory->parent)
                <div class="info-row">
                    <span class="info-label">Vinculado a</span>
                    <span class="info-value">
                        <a href="{{ route('inventory.show', $inventory->parent) }}" style="color: var(--secondary); font-weight: 500;">
                            <i class="ph ph-link" style="vertical-align: middle;"></i> {{ $inventory->parent->name }}
                        </a>
                    </span>
                </div>
                @endif
            </div>
        </div>

        {{-- Card: Fechas --}}
        <div class="card">
            <div class="info-group">
                <div class="info-group-title">
                    <i class="ph ph-calendar"></i> Fechas
                </div>
                <div class="info-row">
                    <span class="info-label">Fecha de compra</span>
                    <span class="info-value">
                        {{ $inventory->purchase_date ? $inventory->purchase_date->format('d/m/Y') : '—' }}
                    </span>
                </div>
                <div class="info-row">
                    <span class="info-label">Fecha de instalación</span>
                    <span class="info-value">
                        {{ $inventory->installation_date ? $inventory->installation_date->format('d/m/Y') : '—' }}
                    </span>
                </div>
                <div class="info-row">
                    <span class="info-label">Inicio de Garantía</span>
                    <span class="info-value">
                        {{ $inventory->warranty_start ? $inventory->warranty_start->format('d/m/Y') : '—' }}
                    </span>
                </div>
                <div class="info-row">
                    <span class="info-label">Garantía hasta</span>
                    <span class="info-value">
                        @if($inventory->warranty_until)
                            {{ $inventory->warranty_until->format('d/m/Y') }}
                            @if($inventory->warranty_until->isFuture())
                                <span class="badge badge-success" style="margin-left: 4px;">Vigente</span>
                            @else
                                <span class="badge badge-danger" style="margin-left: 4px;">Vencida</span>
                            @endif
                        @else
                            —
                        @endif
                    </span>
                </div>
            </div>
        </div>

        {{-- Card: Especificaciones Técnicas --}}
        @if($inventory->features && count(array_filter($inventory->features)) > 0)
            <div class="card">
                <div class="info-group">
                    <div class="info-group-title">
                        <i class="ph ph-cpu"></i> Especificaciones Técnicas
                    </div>
                    @php
                        $featureLabels = [
                            'pc_name' => 'Nombre del equipo',
                            'os' => 'Sistema Operativo',
                            'os_license' => 'Licencia del OS',
                            'processor' => 'Procesador',
                            'ram' => 'Memoria RAM',
                            'disk' => 'Almacenamiento (Disco)',
                            'gpu' => 'Tarjeta gráfica',
                            'office' => 'Office instalado',
                            'office_license' => 'Licencia de Office',
                            'antivirus' => 'Antivirus',
                            'antivirus_license' => 'Licencia de Antivirus',
                            'domain' => 'Dominio o grupo de trabajo',
                            'main_user' => 'Usuario principal',
                            'peripherals' => 'Periféricos',
                            'battery' => 'Estado de batería',
                            'charger' => 'Cargador asignado',
                            'accessories' => 'Accesorios',
                            'screen_size' => 'Tamaño de Pantalla',
                            'video_ports' => 'Puertos de Video',
                            'printer_type' => 'Tipo de Impresión',
                            'connection_type' => 'Tipo de Conexión',
                            'channels' => 'Cantidad de canales',
                            'firmware' => 'Firmware',
                            'admin_user' => 'Usuario administrador',
                            'admin_pass' => 'Contraseña',
                            'ddns_p2p' => 'DDNS o P2P',
                            'technology' => 'Tecnología',
                            'camera_type' => 'Tipo / Canales',
                            'resolution' => 'Resolución',
                            'managed' => 'Administrable',
                            'ports_count' => 'Cantidad de puertos',
                            'speed' => 'Velocidad',
                            'vlan' => 'VLAN configuradas',
                            'rack' => 'Rack',
                            'extension' => 'Extensión',
                            'fxs_ports' => 'Puerto FXS',
                            'voip_operator' => 'Operador VoIP',
                            'wan_ip' => 'IP WAN',
                            'lan_ip' => 'IP LAN',
                            'wifi' => 'Redes WiFi',
                            'mac_address' => 'Dirección MAC',
                        ];
                    @endphp
                    @foreach($inventory->features as $key => $value)
                        @if(!empty($value))
                            <div class="info-row">
                                <span class="info-label">{{ $featureLabels[$key] ?? ucfirst(str_replace('_', ' ', $key)) }}</span>
                                <span class="info-value">{{ is_array($value) ? implode(', ', $value) : $value }}</span>
                            </div>
                        @endif
                    @endforeach
                </div>
            </div>
        @endif

        {{-- Card: Notas --}}
        @if($inventory->notes)
            <div class="card">
                <div class="info-group">
                    <div class="info-group-title">
                        <i class="ph ph-note"></i> Notas
                    </div>
                    <p style="color: var(--text-secondary); font-size: 0.9rem; line-height: 1.6;">{{ $inventory->notes }}</p>
                </div>
            </div>
        @endif
    </div>

    {{-- Historial de Mantenimiento --}}
    <div x-data="{ showMaintenanceModal: false }" style="margin-top: var(--space-xl);">
        <div class="d-flex align-center" style="justify-content: space-between; flex-wrap: wrap; gap: 15px; margin-bottom: var(--space-md);">
            <h2 class="h3" style="margin: 0; display: flex; align-items: center; gap: var(--space-sm);">
                <i class="ph ph-wrench" style="color: var(--primary);"></i>
                Historial de Mejoramiento/Mantenimiento
            </h2>
            <button @click="showMaintenanceModal = true" class="btn btn-primary btn-sm">
                <i class="ph ph-plus"></i> Registrar Actividad
            </button>
        </div>

        <div class="card" style="padding: var(--space-lg);">
            @if($inventory->maintenanceLogs && $inventory->maintenanceLogs->count() > 0)
                <div class="timeline" style="position: relative; padding-left: 2rem;">
                    {{-- Pseudo-elementos de la linea de tiempo deberian ir en CSS, pero agregamos estilo en linea si es necesario, o asumimos CSS de timeline --}}
                    <div style="position: absolute; top: 0; bottom: 0; left: 11px; width: 2px; background: var(--border-color);"></div>
                    
                    @foreach($inventory->maintenanceLogs as $log)
                        <div class="timeline-item" style="position: relative; margin-bottom: var(--space-lg);">
                            <div class="timeline-icon" style="position: absolute; left: -2rem; width: 24px; height: 24px; border-radius: 50%; background: var(--surface); border: 2px solid var(--primary); display: flex; align-items: center; justify-content: center;">
                                <i class="ph ph-wrench" style="font-size: 12px; color: var(--primary);"></i>
                            </div>
                            <div class="timeline-content" style="background: var(--surface-hover); padding: var(--space-md); border-radius: var(--radius-md); border: 1px solid var(--border-color);">
                                <div class="d-flex align-center" style="justify-content: space-between; margin-bottom: var(--space-xs);">
                                    <div class="d-flex align-center gap-sm">
                                        <h4 style="margin: 0;">{{ $log->title }}</h4>
                                        <span class="badge badge-primary">{{ ucfirst($log->type) }}</span>
                                    </div>

                                </div>
                                <p style="color: var(--text-secondary); margin: var(--space-sm) 0; font-size: 0.95rem;">
                                    {{ $log->description }}
                                </p>
                                <div class="d-flex align-center gap-md" style="font-size: 0.85rem; color: var(--text-muted); justify-content: space-between; flex-wrap: wrap;">
                                    <div class="d-flex align-center gap-md">
                                        @if($log->cost)
                                        <span>
                                            <i class="ph ph-currency-dollar" style="color: var(--success);"></i> 
                                            Costo: ${{ number_format($log->cost, 2) }}
                                        </span>
                                        @endif
                                        <span>
                                            <i class="ph ph-user"></i> 
                                            Registrado por: {{ $log->user->name ?? 'Usuario Desconocido' }} el {{ $log->created_at->format('d/m/Y h:i A') }}
                                        </span>
                                    </div>
                                    
                                    <div>
                                        @if($log->is_approved)
                                            @if($log->requires_approval)
                                                <span class="badge" style="background: rgba(40, 167, 69, 0.1); color: #28a745; border: 1px solid #28a745;">
                                                    <i class="ph ph-check-circle" style="margin-right: 4px;"></i>
                                                    Aprobado por {{ $log->approvedBy->name ?? 'Cliente' }} el {{ \Carbon\Carbon::parse($log->approved_at)->format('d/m/Y h:i A') }}
                                                </span>
                                            @else
                                                <span class="badge" style="background: rgba(23, 162, 184, 0.1); color: #17a2b8; border: 1px solid #17a2b8;">
                                                    <i class="ph ph-info" style="margin-right: 4px;"></i> Registro Guardado Directamente
                                                </span>
                                            @endif
                                        @else
                                            @if(auth()->user()->isClient())
                                                <form action="{{ route('inventory.maintenance.approve', [$inventory, $log]) }}" method="POST" style="display: inline;">
                                                    @csrf
                                                    <button type="submit" class="btn btn-sm" style="background: var(--success); color: white; border: none; padding: 4px 10px; border-radius: 4px; cursor: pointer; font-size: 0.8rem; font-weight: bold;">
                                                        <i class="ph ph-check-square-offset"></i> Aprobar Intervención
                                                    </button>
                                                </form>
                                            @else
                                                <span class="badge badge-warning" style="opacity: 0.8;">
                                                    <i class="ph ph-clock" style="margin-right: 4px;"></i> Pendiente de aprobación
                                                </span>
                                            @endif
                                        @endif
                                        @if(auth()->user()->isAdmin())
                                            <form action="{{ route('inventory.maintenance.destroy', [$inventory, $log]) }}" method="POST" style="display: inline; margin-left: 10px;" onsubmit="return confirm('¿Estás seguro de eliminar este registro de mantenimiento? Esta acción no se puede deshacer.');">
                                                @csrf
                                                @method('DELETE')
                                                <button type="submit" class="btn btn-sm btn-ghost text-danger" style="padding: 4px 8px; font-size: 1.1rem;" title="Eliminar registro">
                                                    <i class="ph ph-trash"></i>
                                                </button>
                                            </form>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            @else
                <div class="text-center text-muted" style="padding: var(--space-xl) 0;">
                    <i class="ph ph-clipboard-text" style="font-size: 3rem; opacity: 0.5; margin-bottom: var(--space-sm);"></i>
                    <p>No hay registros de mantenimiento para este equipo.</p>
                </div>
            @endif
        </div>

        {{-- Modal de Alpine.js para Registrar Actividad --}}
        <div x-show="showMaintenanceModal" 
             style="display: none; position: fixed; inset: 0; z-index: 1000; align-items: center; justify-content: center;"
             x-transition.opacity>
            
            <div class="modal-backdrop" 
                 @click="showMaintenanceModal = false"
                 style="position: absolute; inset: 0; background: rgba(0,0,0,0.5); backdrop-filter: blur(4px);"></div>
            
            <div class="card modal-content animate-fadeIn" 
                 style="position: relative; width: 100%; max-width: 500px; max-height: 90vh; overflow-y: auto; z-index: 1001; margin: var(--space-md);">
                
                <div class="modal-header d-flex align-center" style="justify-content: space-between; margin-bottom: var(--space-md); padding-bottom: var(--space-sm); border-bottom: 1px solid var(--border-color);">
                    <h3 class="h4" style="margin: 0;">Registrar Actividad</h3>
                    <button type="button" class="btn btn-ghost btn-icon btn-sm" @click="showMaintenanceModal = false">
                        <i class="ph ph-x"></i>
                    </button>
                </div>

                <form method="POST" action="{{ route('inventory.maintenance.store', $inventory->id) }}">
                    @csrf
                    
                    <div class="form-group" style="margin-bottom: var(--space-md);">
                        <label for="type" class="form-label">Tipo de Actividad <span class="text-danger">*</span></label>
                        <select name="type" id="type" class="form-control" required>
                            <option value="">Seleccione un tipo...</option>
                            <option value="mejoramiento">Mejoramiento</option>
                            <option value="mantenimiento">Mantenimiento</option>
                            <option value="reparacion">Reparación</option>
                            <option value="diagnostico">Diagnóstico</option>
                            <option value="otro">Otro</option>
                        </select>
                    </div>

                    <div class="form-group" style="margin-bottom: var(--space-md);">
                        <label for="title" class="form-label">Título <span class="text-danger">*</span></label>
                        <input type="text" name="title" id="title" class="form-control" required placeholder="Ej. Cambio de memoria RAM">
                    </div>

                    <div class="form-group" style="margin-bottom: var(--space-md);">
                        <label for="description" class="form-label">Descripción <span class="text-danger">*</span></label>
                        <textarea name="description" id="description" class="form-control" rows="3" required placeholder="Detalle las actividades realizadas..."></textarea>
                    </div>

                    <div class="form-group" style="margin-bottom: var(--space-lg);">
                        <input type="hidden" name="maintenance_date" value="{{ date('Y-m-d') }}">
                        <label for="cost" class="form-label">Costo ($)</label>
                        <input type="number" step="0.01" min="0" name="cost" id="cost" class="form-control" placeholder="0.00">
                    </div>

                    <div class="form-group" style="margin-bottom: var(--space-lg); background: var(--surface-hover); padding: 12px; border-radius: 8px; border: 1px solid var(--border-color);">
                        <label class="form-label" style="display: flex; align-items: center; gap: 8px; cursor: pointer; margin: 0;">
                            <input type="checkbox" name="requires_approval" value="1" checked style="width: 16px; height: 16px; cursor: pointer;">
                            <span style="font-weight: 600;">Requiere aprobación del cliente</span>
                        </label>
                        <p class="text-muted" style="margin: 6px 0 0 24px; font-size: 0.85rem;">Si desmarcas esta opción, el registro se guardará directamente en el historial sin enviar notificación para aprobación.</p>
                    </div>

                    <div class="d-flex" style="justify-content: flex-end; gap: var(--space-sm);">
                        <button type="button" class="btn btn-outline" @click="showMaintenanceModal = false">Cancelar</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="ph ph-floppy-disk"></i> Guardar Registro
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<x-signature-modal formId="form-device-report" />

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        if (typeof window.Echo !== 'undefined') {
            window.Echo.private('system')
                .listen('SystemDataChanged', (e) => {
                    if (e.model === 'InventoryItem') {
                        const activeEl = document.activeElement;
                        const isTyping = activeEl && (activeEl.tagName === 'INPUT' || activeEl.tagName === 'TEXTAREA' || activeEl.tagName === 'SELECT') && !activeEl.readOnly && !activeEl.disabled;
                        
                        if (!isTyping) {
                            sessionStorage.setItem('autoRefreshScroll', window.scrollY);
                            window.location.reload();
                        }
                    }
                });
        }
    });
</script>
@endpush
@endsection
