<div class="flex items-center gap-3 mb-6">
    <a href="{{ route('admin.automations.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>
    <h1 class="text-2xl font-bold text-gray-900">{{ $rule ? 'Editar regla' : 'Nueva regla de automatización' }}</h1>
</div>

<form method="POST"
      action="{{ $rule ? route('admin.automations.update', $rule) : route('admin.automations.store') }}">
    @csrf @if($rule) @method('PATCH') @endif

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2 space-y-5">

        {{-- Info básica --}}
        <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">Información</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="md:col-span-2">
                    <label class="block text-xs font-medium text-gray-700 mb-1">Nombre *</label>
                    <input type="text" name="name" value="{{ old('name', $rule?->name) }}"
                           placeholder="Ej: Auto-asignar tickets de red al grupo de infraestructura"
                           class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-700 mb-1">Disparador *</label>
                    <select name="trigger" class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                        @foreach($triggers as $key => $label)
                        <option value="{{ $key }}" {{ old('trigger', $rule?->trigger) === $key ? 'selected' : '' }}>
                            {{ $label }}
                        </option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-gray-700 mb-1">Orden de ejecución</label>
                    <input type="number" name="order" value="{{ old('order', $rule?->order ?? 0) }}" min="0"
                           class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-xs font-medium text-gray-700 mb-1">Descripción</label>
                    <input type="text" name="description" value="{{ old('description', $rule?->description) }}"
                           class="w-full rounded-lg border-gray-300 text-sm focus:ring-blue-500 focus:border-blue-500">
                </div>
            </div>
        </div>

        {{-- Condiciones --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-sm font-semibold text-gray-900">Condiciones (todas deben cumplirse)</h3>
                <button type="button" onclick="addCondition()"
                        class="text-xs text-blue-600 hover:text-blue-800 font-medium">+ Agregar</button>
            </div>
            <div id="conditions-container" class="space-y-2">
                @foreach(old('conditions', $rule?->conditions ?? [[]]) as $i => $cond)
                <div class="condition-row flex items-center gap-2">
                    <select name="conditions[{{ $i }}][field]"
                            class="flex-1 rounded-lg border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                        <option value="">— Campo —</option>
                        @foreach($conditions as $key => $label)
                        <option value="{{ $key }}" {{ ($cond['field'] ?? '') === $key ? 'selected' : '' }}>
                            {{ $label }}
                        </option>
                        @endforeach
                    </select>
                    <select name="conditions[{{ $i }}][operator]"
                            class="rounded-lg border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                        @foreach($operators as $key => $label)
                        <option value="{{ $key }}" {{ ($cond['operator'] ?? 'equals') === $key ? 'selected' : '' }}>
                            {{ $label }}
                        </option>
                        @endforeach
                    </select>
                    <input type="text" name="conditions[{{ $i }}][value]"
                           value="{{ $cond['value'] ?? '' }}"
                           placeholder="Valor"
                           class="flex-1 rounded-lg border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                    <button type="button" onclick="this.closest('.condition-row').remove()"
                            class="text-red-400 hover:text-red-600 text-sm font-bold">✕</button>
                </div>
                @endforeach
            </div>
            <p class="text-xs text-gray-400 mt-2">
                Para prioridad/categoría/estado usa el ID numérico. Deja vacías las condiciones para ejecutar siempre.
            </p>
        </div>

        {{-- Acciones --}}
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-sm font-semibold text-gray-900">Acciones a ejecutar</h3>
                <button type="button" onclick="addAction()"
                        class="text-xs text-blue-600 hover:text-blue-800 font-medium">+ Agregar acción</button>
            </div>
            <div id="actions-container" class="space-y-3">
                @foreach(old('actions', $rule?->actions ?? [[]]) as $i => $action)
                <div class="action-row bg-gray-50 rounded-lg p-3 space-y-2">
                    <div class="flex items-center gap-2">
                        <select name="actions[{{ $i }}][type]"
                                class="flex-1 rounded-lg border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                            <option value="">— Tipo de acción —</option>
                            @foreach($actionTypes as $key => $label)
                            <option value="{{ $key }}" {{ ($action['type'] ?? '') === $key ? 'selected' : '' }}>
                                {{ $label }}
                            </option>
                            @endforeach
                        </select>
                        <button type="button" onclick="this.closest('.action-row').remove()"
                                class="text-red-400 hover:text-red-600 text-sm font-bold">✕</button>
                    </div>
                    {{-- Parámetros según tipo --}}
                    <div class="grid grid-cols-2 gap-2">
                        <div>
                            <label class="text-xs text-gray-500">Agente ID (para assign_agent)</label>
                            <select name="actions[{{ $i }}][params][agent_id]"
                                    class="w-full rounded border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                                <option value="">— Auto (round-robin) —</option>
                                @foreach($agents as $agent)
                                <option value="{{ $agent->id }}" {{ ($action['params']['agent_id'] ?? '') == $agent->id ? 'selected' : '' }}>
                                    {{ $agent->name }}
                                </option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="text-xs text-gray-500">Prioridad (para change_priority)</label>
                            <select name="actions[{{ $i }}][params][priority_id]"
                                    class="w-full rounded border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                                <option value="">— Selecciona —</option>
                                @foreach($priorities as $p)
                                <option value="{{ $p->id }}" {{ ($action['params']['priority_id'] ?? '') == $p->id ? 'selected' : '' }}>
                                    {{ $p->name }}
                                </option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="text-xs text-gray-500">Estado (para change_status)</label>
                            <select name="actions[{{ $i }}][params][status_id]"
                                    class="w-full rounded border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                                <option value="">— Selecciona —</option>
                                @foreach($statuses as $s)
                                <option value="{{ $s->id }}" {{ ($action['params']['status_id'] ?? '') == $s->id ? 'selected' : '' }}>
                                    {{ $s->name }}
                                </option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="text-xs text-gray-500">Destinatario notificación</label>
                            <select name="actions[{{ $i }}][params][recipient]"
                                    class="w-full rounded border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                                <option value="assignee"  {{ ($action['params']['recipient'] ?? 'assignee') === 'assignee'  ? 'selected' : '' }}>Agente asignado</option>
                                <option value="requester" {{ ($action['params']['recipient'] ?? '') === 'requester' ? 'selected' : '' }}>Solicitante</option>
                                <option value="admins"    {{ ($action['params']['recipient'] ?? '') === 'admins'    ? 'selected' : '' }}>Administradores</option>
                            </select>
                        </div>
                        <div class="col-span-2">
                            <label class="text-xs text-gray-500">Texto (para comentario/notificación). Usa {{ticket}}, {{solicitante}}</label>
                            <input type="text" name="actions[{{ $i }}][params][body]"
                                   value="{{ $action['params']['body'] ?? '' }}"
                                   placeholder="Ej: El ticket {{ticket}} fue asignado automáticamente"
                                   class="w-full rounded border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
        </div>

    </div>

    {{-- Panel lateral --}}
    <div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 sticky top-4">
            <h3 class="text-sm font-semibold text-gray-900 mb-4">Estado</h3>
            <label class="flex items-center gap-2 cursor-pointer mb-4">
                <input type="checkbox" name="active" value="1"
                       {{ old('active', $rule?->active ?? true) ? 'checked' : '' }}
                       class="rounded border-gray-300 text-blue-600">
                <span class="text-sm text-gray-700">Regla activa</span>
            </label>
            @if($rule)
            <dl class="space-y-2 text-xs mb-4 pb-4 border-b border-gray-100">
                <div class="flex justify-between">
                    <dt class="text-gray-500">Ejecuciones</dt>
                    <dd class="font-semibold">{{ $rule->executions }}</dd>
                </div>
                @if($rule->last_executed_at)
                <div class="flex justify-between">
                    <dt class="text-gray-500">Última ejecución</dt>
                    <dd class="text-gray-700">{{ $rule->last_executed_at->format('d/m/y H:i') }}</dd>
                </div>
                @endif
            </dl>
            @endif
            <button type="submit"
                    class="w-full py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition mb-2">
                {{ $rule ? 'Guardar cambios' : 'Crear regla' }}
            </button>
            <a href="{{ route('admin.automations.index') }}"
               class="block w-full py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 transition text-center">
                Cancelar
            </a>
        </div>
    </div>
    </div>
</form>

<script>
let condIdx = {{ count(old('conditions', $rule?->conditions ?? [[]]))  }};
let actIdx  = {{ count(old('actions',    $rule?->actions    ?? [[]])) }};

function addCondition() {
    const c = condIdx++;
    const div = document.createElement('div');
    div.className = 'condition-row flex items-center gap-2';
    div.innerHTML = `
        <select name="conditions[${c}][field]" class="flex-1 rounded-lg border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
            <option value="">— Campo —</option>
            @foreach($conditions as $key => $label)
            <option value="{{ $key }}">{{ $label }}</option>
            @endforeach
        </select>
        <select name="conditions[${c}][operator]" class="rounded-lg border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
            @foreach($operators as $key => $label)
            <option value="{{ $key }}">{{ $label }}</option>
            @endforeach
        </select>
        <input type="text" name="conditions[${c}][value]" placeholder="Valor"
               class="flex-1 rounded-lg border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
        <button type="button" onclick="this.closest('.condition-row').remove()" class="text-red-400 hover:text-red-600 text-sm font-bold">✕</button>
    `;
    document.getElementById('conditions-container').appendChild(div);
}

function addAction() {
    const a = actIdx++;
    const div = document.createElement('div');
    div.className = 'action-row bg-gray-50 rounded-lg p-3 space-y-2';
    div.innerHTML = `
        <div class="flex items-center gap-2">
            <select name="actions[${a}][type]" class="flex-1 rounded-lg border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
                <option value="">— Tipo de acción —</option>
                @foreach($actionTypes as $key => $label)
                <option value="{{ $key }}">{{ $label }}</option>
                @endforeach
            </select>
            <button type="button" onclick="this.closest('.action-row').remove()" class="text-red-400 hover:text-red-600 text-sm font-bold">✕</button>
        </div>
        <div>
            <label class="text-xs text-gray-500">Texto / cuerpo</label>
            <input type="text" name="actions[${a}][params][body]" placeholder="Ej: Ticket {{ticket}} escalado automáticamente"
                   class="w-full rounded border-gray-300 text-xs focus:ring-blue-500 focus:border-blue-500">
        </div>
    `;
    document.getElementById('actions-container').appendChild(div);
}
</script>
