@extends('layouts.gestao')

@section('title', 'Editar Pergunta')

@section('content')
<div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="flex items-center gap-2 text-sm text-gray-500">
        <a href="{{ route('protocolos.index') }}" class="hover:text-gray-700">Protocolos</a>
        <span>/</span>
        <a href="{{ route('protocolos.perguntas', $protocolo) }}" class="hover:text-gray-700">Perguntas</a>
        <span>/</span>
        <span class="text-gray-700">Editar Pergunta</span>
    </div>

    <div class="mt-2 flex items-center justify-between">
        <div>
            <h1 class="text-2xl font-semibold tracking-tight text-gray-900">Editar Pergunta</h1>
            <p class="text-sm text-gray-500">Altere o texto, a ordem e as opções da pergunta.</p>
        </div>
        <a href="{{ route('protocolos.perguntas', $protocolo) }}" class="hidden sm:inline-flex items-center gap-2 text-sm px-3 py-2 rounded-lg border border-gray-200 text-gray-700 hover:bg-gray-50">Voltar</a>
    </div>

    @if ($errors->any())
        <div class="mt-4 rounded-lg border border-red-200 bg-red-50 text-red-800 px-4 py-3">
            <div class="font-medium">Ocorreram erros ao enviar o formulário:</div>
            <ul class="mt-2 list-disc list-inside text-sm">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form method="POST" action="{{ route('protocolos.perguntas.update', [$protocolo, $pergunta]) }}" class="mt-6 bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden px-4 sm:px-6 py-6 space-y-6" autocomplete="off" novalidate>
        @csrf
        @method('PUT')

        <div class="grid grid-cols-1 md:grid-cols-6 gap-4">
            <div class="md:col-span-4">
                <label class="block text-sm font-medium text-gray-700">Pergunta <span class="text-red-600">*</span></label>
                <input type="text" name="texto" value="{{ old('texto', $pergunta->texto) }}" class="mt-1 block w-full rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent {{ $errors->has('texto') ? 'ring-2 ring-red-500 border-transparent' : '' }}" required>
                @if($errors->has('texto'))
                    <p class="mt-1 text-xs text-red-600">{{ $errors->first('texto') }}</p>
                @else
                    <p class="mt-1 text-xs text-gray-500">Ex.: "Como você avalia seu nível de estresse hoje?"</p>
                @endif
            </div>

            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700">Ordem <span class="text-red-600">*</span></label>
                <input type="number" name="ordem" value="{{ old('ordem', $pergunta->ordem) }}" class="mt-1 block w-full rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent {{ $errors->has('ordem') ? 'ring-2 ring-red-500 border-transparent' : '' }}">
                @if($errors->has('ordem'))
                    <p class="mt-1 text-xs text-red-600">{{ $errors->first('ordem') }}</p>
                @else
                    <p class="mt-1 text-xs text-gray-500">A posição em que a pergunta aparecerá.</p>
                @endif
            </div>
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Opções <span class="text-red-600">*</span></label>
            <div id="opcoes-container" class="space-y-2">
                @php $oldOpcoes = old('opcoes', $pergunta->opcoes->toArray()); @endphp
                @foreach($oldOpcoes as $idx => $op)
                    <div class="opcao-row flex gap-2">
                        <input type="hidden" name="opcoes[{{ $idx }}][id]" value="{{ $op['id'] ?? '' }}">
                        <input type="text" name="opcoes[{{ $idx }}][texto]" value="{{ $op['texto'] ?? '' }}" placeholder="Texto" class="flex-1 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        <input type="number" name="opcoes[{{ $idx }}][pontuacao]" value="{{ $op['pontuacao'] ?? '' }}" placeholder="Pontuação" class="w-32 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        <button type="button" class="rm-opcao inline-flex items-center justify-center w-10 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50" aria-label="Remover opção">&times;</button>
                    </div>
                @endforeach
            </div>
            <div class="mt-2 flex items-center gap-3">
                <button type="button" id="add-opcao" class="text-sm inline-flex items-center gap-2 text-blue-700 hover:text-blue-800">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor"><path d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z"/></svg>
                    Adicionar opção
                </button>
                <span class="text-xs text-gray-500">Inclua pelo menos uma opção.</span>
            </div>
            @if($errors->has('opcoes'))
                <p class="mt-2 text-xs text-red-600">{{ $errors->first('opcoes') }}</p>
            @endif
        </div>

        <div class="pt-2">
            <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg">Atualizar Pergunta</button>
        </div>
    </form>
</div>

<script>
    (function(){
        const container = document.getElementById('opcoes-container');
        const btnAdd = document.getElementById('add-opcao');
        if(!container || !btnAdd) return;

        const rowTemplate = (i) => `
            <div class=\"opcao-row flex gap-2\">
                <input type=\"hidden\" name=\"opcoes[${i}][id]\">
                <input type=\"text\" name=\"opcoes[${i}][texto]\" placeholder=\"Texto\" class=\"flex-1 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500\" required>
                <input type=\"number\" name=\"opcoes[${i}][pontuacao]\" placeholder=\"Pontuação\" class=\"w-32 rounded-lg border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500\" required>
                <button type=\"button\" class=\"rm-opcao inline-flex items-center justify-center w-10 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50\" aria-label=\"Remover opção\">&times;</button>
            </div>`;

        const countRows = () => container.querySelectorAll('.opcao-row').length;
        let idx = countRows();

        btnAdd.addEventListener('click', () => {
            container.insertAdjacentHTML('beforeend', rowTemplate(idx++));
        });

        container.addEventListener('click', (e) => {
            if(e.target.classList.contains('rm-opcao')){
                const rows = container.querySelectorAll('.opcao-row');
                if(rows.length <= 1) return;
                e.target.closest('.opcao-row').remove();
            }
        });
    })();
</script>
@endsection

