@extends('layouts.app')

@section('title', 'Soporte | Veltrix v2')
@section('page_title', 'Soporte')
@section('page_subtitle', 'Gestion operativa en tiempo real')
@section('page_icon', 'bx bx-menu-alt-left')

@section('content')
    @php
        $ticketRows = $tickets instanceof \Illuminate\Support\Collection ? $tickets : collect($tickets ?? []);
        $eventMap = is_array($eventsByTicket ?? null) ? $eventsByTicket : [];
        $oldPriority = (string) old('prioridad', 'media');
    @endphp

    <div class="container-fluid px-4 py-4">
        @if ($errors->any())
            <div class="alert alert-danger mb-3">
                {{ $errors->first() }}
            </div>
        @endif

        <div class="row g-3 mb-4">
            <div class="col-lg-5">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h5 mb-3">Crear Ticket de Soporte</h2>
                        <form action="{{ route('soporte.tickets.store') }}" method="post" enctype="multipart/form-data">
                            @csrf
                            <div class="mb-2">
                                <label class="form-label">Asunto</label>
                                <input class="form-control" name="asunto" maxlength="180" value="{{ (string) old('asunto', '') }}" required>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Prioridad</label>
                                <select class="form-select" name="prioridad" required>
                                    <option value="baja" @selected($oldPriority === 'baja')>Baja</option>
                                    <option value="media" @selected($oldPriority === 'media')>Media</option>
                                    <option value="alta" @selected($oldPriority === 'alta')>Alta</option>
                                    <option value="critica" @selected($oldPriority === 'critica')>Crítica</option>
                                </select>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Descripción</label>
                                <textarea class="form-control" name="descripcion" rows="4" maxlength="2000" required>{{ (string) old('descripcion', '') }}</textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Imagen adjunta (opcional)</label>
                                <input type="file" class="form-control" name="adjunto" accept="image/png,image/jpeg,image/webp,image/gif">
                                <small class="text-muted">Formatos: JPG, PNG, WEBP, GIF. Máximo 5MB.</small>
                            </div>
                            <button class="btn btn-primary w-100" type="submit">Enviar ticket</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-7">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <h2 class="h5 mb-2">¿Cómo funciona?</h2>
                        <p class="text-muted mb-2">
                            Crea el ticket desde tu empresa y el superadministrador lo verá en su panel de soporte para responder y resolver.
                        </p>
                        <ul class="mb-0 text-muted">
                            <li>Incluye asunto claro y descripción detallada.</li>
                            <li>Adjunta imagen cuando aplique para acelerar la solución.</li>
                            <li>Usa comentarios para seguimiento del caso.</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <h1 class="h4 mb-3">Mis Tickets</h1>
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Asunto</th>
                                <th>Estado / Prioridad</th>
                                <th>Asignado</th>
                                <th>Actualizado</th>
                                <th>Acción</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse ($ticketRows as $ticket)
                                @php
                                    $ticketId = (int) data_get($ticket, 'id', 0);
                                    $status = (string) data_get($ticket, 'estado', 'abierto');
                                    $priority = (string) data_get($ticket, 'prioridad', 'media');
                                    $statusClass = match ($status) {
                                        'abierto' => 'text-bg-warning',
                                        'en_proceso' => 'text-bg-primary',
                                        'resuelto', 'cerrado' => 'text-bg-success',
                                        default => 'text-bg-secondary',
                                    };
                                    $priorityClass = match ($priority) {
                                        'critica' => 'text-bg-danger',
                                        'alta' => 'text-bg-warning',
                                        'media' => 'text-bg-primary',
                                        default => 'text-bg-secondary',
                                    };
                                    $events = is_array($eventMap[$ticketId] ?? null) ? $eventMap[$ticketId] : [];
                                @endphp

                                <tr>
                                    <td>#{{ $ticketId }}</td>
                                    <td>
                                        <strong>{{ (string) data_get($ticket, 'asunto', '') }}</strong>
                                        <small class="d-block text-muted text-truncate" style="max-width: 320px;">
                                            {{ (string) data_get($ticket, 'descripcion', '') }}
                                        </small>
                                    </td>
                                    <td>
                                        <span class="badge {{ $statusClass }}">{{ $status }}</span>
                                        <span class="badge {{ $priorityClass }}">{{ $priority }}</span>
                                    </td>
                                    <td>{{ (string) data_get($ticket, 'asignado_a', 'Sin asignar') }}</td>
                                    <td>{{ (string) data_get($ticket, 'updated_at', '-') }}</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#supportTicket{{ $ticketId }}">
                                            Ver detalle
                                        </button>
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="6" class="bg-light">
                                        <div class="collapse" id="supportTicket{{ $ticketId }}">
                                            <div class="p-2 border rounded bg-white mb-2">
                                                <form action="{{ route('soporte.tickets.comment', ['ticket' => $ticketId]) }}" method="post" enctype="multipart/form-data" class="row g-2">
                                                    @csrf
                                                    <div class="col-md-8">
                                                        <label class="form-label">Comentario para soporte</label>
                                                        <input class="form-control" name="mensaje" maxlength="1500" placeholder="Escribe actualización del caso...">
                                                    </div>
                                                    <div class="col-md-3">
                                                        <label class="form-label">Imagen (opcional)</label>
                                                        <input type="file" class="form-control" name="adjunto" accept="image/png,image/jpeg,image/webp,image/gif">
                                                    </div>
                                                    <div class="col-md-1 d-flex align-items-end">
                                                        <button class="btn btn-sm btn-outline-primary w-100" type="submit">Enviar</button>
                                                    </div>
                                                </form>
                                            </div>

                                            <div class="p-2 border rounded bg-white">
                                                <strong class="d-block mb-2">Historial</strong>
                                                @if ($events !== [])
                                                    <ul class="list-group list-group-flush">
                                                        @foreach (array_slice($events, 0, 15) as $event)
                                                            @php
                                                                $attachment = is_array(data_get($event, 'adjunto')) ? data_get($event, 'adjunto') : null;
                                                                $message = trim((string) data_get($event, 'mensaje_texto', ''));
                                                                if ($message === '') {
                                                                    $message = 'Adjunto sin comentario.';
                                                                }
                                                            @endphp
                                                            <li class="list-group-item px-0 py-2">
                                                                <div class="d-flex justify-content-between gap-2">
                                                                    <span>
                                                                        <span class="badge text-bg-light border me-1">{{ (string) data_get($event, 'tipo', '-') }}</span>
                                                                        {{ $message }}
                                                                    </span>
                                                                    <small class="text-muted text-nowrap">{{ (string) data_get($event, 'created_at', '-') }}</small>
                                                                </div>
                                                                @if ($attachment)
                                                                    <div class="mt-1">
                                                                        <a href="{{ (string) data_get($attachment, 'url', '#') }}" target="_blank" rel="noopener">
                                                                            Ver adjunto: {{ (string) data_get($attachment, 'name', 'imagen') }}
                                                                        </a>
                                                                        @if ((bool) data_get($attachment, 'is_image', false))
                                                                            <div class="mt-2">
                                                                                <img
                                                                                    src="{{ (string) data_get($attachment, 'url', '') }}"
                                                                                    alt="{{ (string) data_get($attachment, 'name', 'Adjunto') }}"
                                                                                    style="max-width: 220px; width: 100%; border: 1px solid #dce4f4; border-radius: 8px;"
                                                                                >
                                                                            </div>
                                                                        @endif
                                                                    </div>
                                                                @endif
                                                                <small class="text-muted d-block">
                                                                    {{ (string) data_get($event, 'usuario', 'Sistema') }}
                                                                    @if ((string) data_get($event, 'estado_anterior', '') !== '' || (string) data_get($event, 'estado_nuevo', '') !== '')
                                                                        | Estado: {{ (string) data_get($event, 'estado_anterior', '-') }} -> {{ (string) data_get($event, 'estado_nuevo', '-') }}
                                                                    @endif
                                                                </small>
                                                            </li>
                                                        @endforeach
                                                    </ul>
                                                @else
                                                    <small class="text-muted">Sin eventos todavía.</small>
                                                @endif
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">No hay tickets creados todavía.</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
@endsection
