@extends('layouts.app')

@section('title', 'Tickets')
@section('page-title', 'Gestión de Tickets')

@section('content')
<x-breadcrumb :items="[
    ['label' => 'Tickets', 'icon' => 'ticket', 'active' => true]
]" />

<div class="row mb-3">
    <div class="col-md-6">
        <form method="GET" action="{{ route('tickets.index') }}">
            <div class="input-group">
                <input type="text" class="form-control" name="search" placeholder="Buscar tickets..." value="{{ request('search') }}">
                <button class="btn btn-outline-secondary" type="submit">
                    <i class="bi bi-search"></i>
                </button>
            </div>
        </form>
    </div>
    <div class="col-md-6 text-end">
        <a href="{{ route('tickets.create') }}" class="btn btn-primary">
            <i class="bi bi-plus-circle me-2"></i>Nuevo Ticket
        </a>
    </div>
</div>

<!-- Filters -->
<div class="card mb-3">
    <div class="card-body">
        <form method="GET" action="{{ route('tickets.index') }}" id="filterForm">
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">
                        Estado
                        <i class="bi bi-info-circle help-icon" 
                           data-bs-toggle="tooltip" 
                           data-bs-placement="top" 
                           title="Filtra tickets por su estado actual: Abierto (nuevo), En Progreso (trabajando), Resuelto (solucionado) o Cerrado (finalizado)"></i>
                    </label>
                    <select name="status" class="form-select" onchange="document.getElementById('filterForm').submit()">
                        <option value="">Todos</option>
                        <option value="abierto" {{ request('status') == 'abierto' ? 'selected' : '' }}>Abierto</option>
                        <option value="en_progreso" {{ request('status') == 'en_progreso' ? 'selected' : '' }}>En Progreso</option>
                        <option value="resuelto" {{ request('status') == 'resuelto' ? 'selected' : '' }}>Resuelto</option>
                        <option value="cerrado" {{ request('status') == 'cerrado' ? 'selected' : '' }}>Cerrado</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">
                        Prioridad
                        <i class="bi bi-info-circle help-icon" 
                           data-bs-toggle="tooltip" 
                           data-bs-placement="top" 
                           title="Nivel de urgencia: Baja (puede esperar), Media (normal), Alta (pronto) o Crítica (inmediato)"></i>
                    </label>
                    <select name="priority" class="form-select" onchange="document.getElementById('filterForm').submit()">
                        <option value="">Todas</option>
                        <option value="baja" {{ request('priority') == 'baja' ? 'selected' : '' }}>Baja</option>
                        <option value="media" {{ request('priority') == 'media' ? 'selected' : '' }}>Media</option>
                        <option value="alta" {{ request('priority') == 'alta' ? 'selected' : '' }}>Alta</option>
                        <option value="critica" {{ request('priority') == 'critica' ? 'selected' : '' }}>Crítica</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">
                        Proyecto
                        <i class="bi bi-info-circle help-icon" 
                           data-bs-toggle="tooltip" 
                           data-bs-placement="top" 
                           title="Filtra tickets asociados a un proyecto específico"></i>
                    </label>
                    <select name="project_id" class="form-select" onchange="document.getElementById('filterForm').submit()">
                        <option value="">Todos</option>
                        @foreach($projects as $project)
                        <option value="{{ $project->id }}" {{ request('project_id') == $project->id ? 'selected' : '' }}>
                            {{ $project->name }}
                        </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">&nbsp;</label>
                    <div>
                        @if(request()->hasAny(['status', 'priority', 'project_id', 'search']))
                        <a href="{{ route('tickets.index') }}" class="btn btn-outline-secondary w-100">
                            <i class="bi bi-x-circle me-2"></i>Limpiar Filtros
                        </a>
                        @endif
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Tickets Table -->
<div class="card">
    <div class="card-body">
        <!-- Mobile Card View -->
        @foreach($tickets as $ticket)
        <div class="ticket-card-mobile priority-{{ $ticket->priority }}">
            <div class="ticket-card-header">
                <div class="ticket-card-number">
                    {{ $ticket->ticket_number }}
                    @if(isset($ticket->unreadCount) && $ticket->unreadCount > 0)
                        <span class="badge bg-danger ms-1" style="font-size: 0.7rem;">
                            <i class="bi bi-chat-fill"></i> {{ $ticket->unreadCount }}
                        </span>
                    @endif
                </div>
                <div class="ticket-card-badges">
                    <span class="badge badge-priority-{{ $ticket->priority }}">
                        {{ ucfirst($ticket->priority) }}
                    </span>
                    <span class="badge badge-status-{{ $ticket->status }}">
                        {{ ucfirst(str_replace('_', ' ', $ticket->status)) }}
                    </span>
                </div>
            </div>
            
            <div class="ticket-card-title">
                <a href="{{ route('tickets.show', $ticket) }}" class="text-decoration-none text-dark">
                    {{ $ticket->title }}
                </a>
            </div>
            
            <div class="ticket-card-meta">
                @if($ticket->project)
                <div class="ticket-card-meta-item">
                    <i class="bi bi-folder"></i>
                    <span>{{ $ticket->project->name }}</span>
                </div>
                @endif
                
                <div class="ticket-card-meta-item">
                    <i class="bi bi-person"></i>
                    <span>{{ $ticket->requester->name }}</span>
                </div>
                
                @if($ticket->assignedUser)
                <div class="ticket-card-meta-item">
                    <i class="bi bi-person-check"></i>
                    <span>Asignado a: {{ $ticket->assignedUser->name }}</span>
                </div>
                @endif
                
                <div class="ticket-card-meta-item">
                    <i class="bi bi-calendar"></i>
                    <span>{{ $ticket->created_at->format('d/m/Y H:i') }}</span>
                </div>
            </div>
            
            <div class="ticket-card-footer">
                <div>
                    @if($ticket->isOverdue())
                    <span class="badge bg-danger">
                        <i class="bi bi-exclamation-triangle"></i> Vencido
                    </span>
                    @endif
                </div>
                <div class="btn-group btn-group-sm">
                    <a href="{{ route('tickets.show', $ticket) }}" class="btn btn-outline-primary btn-sm">
                        <i class="bi bi-eye"></i> Ver
                    </a>
                </div>
            </div>
        </div>
        @endforeach
        
        <!-- Desktop Table View -->
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead>
                    <tr>
                        <th style="width: 100px;">ID</th>
                        <th>Título</th>
                        <th>Proyecto</th>
                        <th>Solicitante</th>
                        <th>Asignado a</th>
                        <th>Prioridad</th>
                        <th>Estado</th>
                        @if(in_array(auth()->user()->role, ['responsable', 'ingeniero', 'supervisor', 'administrador']))
                        <th style="width: 100px;">Tiempo</th>
                        @endif
                        <th style="width: 120px;">Fecha</th>
                        <th style="width: 100px;">Acciones</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($tickets as $ticket)
                    <tr>
                        <td>
                            <strong>{{ $ticket->ticket_number }}</strong>
                            @if(isset($ticket->unreadCount) && $ticket->unreadCount > 0)
                                <span class="badge bg-danger ms-1" title="Comentarios nuevos">
                                    <i class="bi bi-chat-fill"></i> {{ $ticket->unreadCount }}
                                </span>
                            @endif
                        </td>
                        <td>
                            <a href="{{ route('tickets.show', $ticket) }}" class="text-decoration-none">
                                {{ Str::limit($ticket->title, 50) }}
                            </a>
                            @if($ticket->isOverdue())
                            <i class="bi bi-exclamation-triangle-fill text-danger ms-1" title="Vencido"></i>
                            @endif
                        </td>
                        <td>
                            @if($ticket->project)
                            <span class="badge bg-secondary">{{ $ticket->project->name }}</span>
                            @else
                            <span class="text-muted">-</span>
                            @endif
                        </td>
                        <td>{{ $ticket->requester->name }}</td>
                        <td>
                            @if($ticket->assignedUser)
                            {{ $ticket->assignedUser->name }}
                            @else
                            <span class="text-muted">Sin asignar</span>
                            @endif
                        </td>
                        <td>
                            <span class="badge badge-priority-{{ $ticket->priority }}"
                                  data-bs-toggle="tooltip"
                                  data-bs-placement="top"
                                  title="@if($ticket->priority == 'critica')Atención urgente requerida - Impacto crítico en operaciones @elseif($ticket->priority == 'alta')Alta prioridad - Requiere atención pronta @elseif($ticket->priority == 'media')Prioridad normal - Atención en orden de llegada @else Prioridad baja - Puede procesarse después @endif">
                                {{ ucfirst($ticket->priority) }}
                            </span>
                        </td>
                        <td>
                            <span class="badge badge-status-{{ $ticket->status }}"
                                  data-bs-toggle="tooltip"
                                  data-bs-placement="top"
                                  title="@if($ticket->status == 'abierto')Ticket nuevo - Pendiente de asignación @elseif($ticket->status == 'en_progreso')En proceso - Asignado y trabajando @elseif($ticket->status == 'resuelto')Resuelto - Esperando confirmación del solicitante @else Cerrado - Ticket finalizado @endif">
                                {{ ucfirst(str_replace('_', ' ', $ticket->status)) }}
                            </span>
                        </td>
                        @if(in_array(auth()->user()->role, ['responsable', 'ingeniero', 'supervisor', 'administrador']))
                        <td>
                            @php
                                $totalTime = $ticket->getTotalWorkTime();
                            @endphp
                            @if($totalTime > 0)
                                <span class="badge bg-info" title="Tiempo total invertido">
                                    <i class="bi bi-clock"></i> {{ \App\Models\TicketWorkSession::formatDuration($totalTime) }}
                                </span>
                            @else
                                <span class="text-muted">-</span>
                            @endif
                        </td>
                        @endif
                        <td>{{ $ticket->created_at->format('d/m/Y') }}</td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <a href="{{ route('tickets.show', $ticket) }}" 
                                   class="btn btn-outline-primary" 
                                   data-bs-toggle="tooltip"
                                   data-bs-placement="top"
                                   title="Ver detalles del ticket">
                                    <i class="bi bi-eye"></i>
                                </a>
                                @if(auth()->user()->hasRole(['administrador', 'supervisor']) || auth()->id() == $ticket->requester_id)
                                <a href="{{ route('tickets.edit', $ticket) }}" 
                                   class="btn btn-outline-secondary"
                                   data-bs-toggle="tooltip"
                                   data-bs-placement="top"
                                   title="Editar ticket">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                @endif
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="10" class="p-0">
                            <x-empty-state 
                                icon="ticket"
                                title="No hay tickets para mostrar"
                                description="No se encontraron tickets con los filtros seleccionados. Intenta ajustar los criterios de búsqueda o crea un nuevo ticket."
                                :action="route('tickets.create')"
                                actionText="Crear Primer Ticket"
                                actionIcon="plus-circle"
                            />
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        
        <div class="mt-3">
            {{ $tickets->links() }}
        </div>
    </div>
</div>
@endsection
