@php
    /** @var ?\App\Models\InvoiceBillingRule $rule */
    $rule = $rule ?? null;
    $isEdit = isset($rule) && $rule?->exists;
@endphp

<x-admin.validation-errors />

<form method="POST"
      action="{{ $isEdit ? route('admin.billing.rules.update', $rule) : route('admin.billing.rules.store') }}"
      id="ruleForm">
    @csrf
    @if($isEdit)@method('PUT')@endif

    <x-admin.card>
        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label">{{ __('admin/billing-rules.fields_name') }} <span class="text-danger">*</span></label>
                <input type="text" name="name" class="form-control @error('name') is-invalid @enderror"
                       value="{{ old('name', $rule?->name) }}" required maxlength="120">
                @error('name') <div class="invalid-feedback">{{ $message }}</div> @enderror
            </div>
            <div class="col-md-3 mb-3">
                <label class="form-label">{{ __('admin/billing-rules.fields_priority') }} <span class="text-danger">*</span></label>
                <input type="number" name="priority" class="form-control @error('priority') is-invalid @enderror"
                       value="{{ old('priority', $rule?->priority ?? 100) }}" min="0" max="9999" required>
                <div class="form-text small">{{ __('admin/billing-rules.fields_priority_help') }}</div>
                @error('priority') <div class="invalid-feedback">{{ $message }}</div> @enderror
            </div>
            <div class="col-md-3 mb-3">
                <label class="form-label d-block">{{ __('admin/billing-rules.fields_active') }}</label>
                <div class="form-check form-switch mt-2">
                    <input type="checkbox" name="is_active" value="1" class="form-check-input" id="is_active"
                           {{ old('is_active', $rule?->is_active ?? true) ? 'checked' : '' }}>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-12 mb-3">
                <div class="form-check form-switch">
                    <input type="checkbox" name="is_fallback" value="1" class="form-check-input" id="is_fallback"
                           {{ old('is_fallback', $rule?->is_fallback ?? false) ? 'checked' : '' }}>
                    <label class="form-check-label" for="is_fallback">
                        {{ __('admin/billing-rules.fallback_label') }}
                    </label>
                </div>
                <div class="form-text small">{{ __('admin/billing-rules.fallback_help') }}</div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6 mb-3">
                <label class="form-label">{{ __('admin/billing-rules.fields_events') }} <span class="text-danger">*</span></label>
                @php $selectedEvents = old('events', $rule?->events ?? []); @endphp
                @foreach(\App\Models\InvoiceBillingRule::ALL_EVENTS as $event)
                    <div class="form-check">
                        <input type="checkbox" name="events[]" value="{{ $event }}" class="form-check-input"
                               id="event_{{ $event }}"
                               {{ in_array($event, $selectedEvents) ? 'checked' : '' }}>
                        <label class="form-check-label" for="event_{{ $event }}">
                            {{ __('admin/billing-rules.events_'.$event) }}
                        </label>
                    </div>
                @endforeach
                @error('events') <div class="text-danger small mt-1">{{ $message }}</div> @enderror
            </div>

            <div class="col-md-6">
                <div class="mb-3">
                    <label class="form-label">{{ __('admin/billing-rules.fields_action') }} <span class="text-danger">*</span></label>
                    @php $selectedAction = old('rule_action', $rule?->action ?? 'dispatch'); @endphp
                    <div class="form-check">
                        <input type="radio" name="rule_action" value="dispatch" id="action_dispatch" class="form-check-input"
                               {{ $selectedAction === 'dispatch' ? 'checked' : '' }}>
                        <label class="form-check-label" for="action_dispatch">{{ __('admin/billing-rules.actions_dispatch') }}</label>
                    </div>
                    <div class="form-check">
                        <input type="radio" name="rule_action" value="skip" id="action_skip" class="form-check-input"
                               {{ $selectedAction === 'skip' ? 'checked' : '' }}>
                        <label class="form-check-label" for="action_skip">{{ __('admin/billing-rules.actions_skip') }}</label>
                    </div>
                </div>

                <div class="mb-3" id="moduleField">
                    <label class="form-label">{{ __('admin/billing-rules.fields_module') }}</label>
                    <select name="billing_module_id" class="form-select @error('billing_module_id') is-invalid @enderror">
                        <option value="">—</option>
                        @foreach($modules as $m)
                            <option value="{{ $m->id }}" {{ old('billing_module_id', $rule?->billing_module_id) == $m->id ? 'selected' : '' }}>
                                {{ $m->display_name }} ({{ $m->type }})
                            </option>
                        @endforeach
                    </select>
                    @error('billing_module_id') <div class="invalid-feedback">{{ $message }}</div> @enderror
                </div>

                <div class="mb-3">
                    <label class="form-label">{{ __('admin/billing-rules.fields_delay_days') }}</label>
                    <input type="number" name="dispatch_delay_days" class="form-control"
                           value="{{ old('dispatch_delay_days', $rule?->dispatch_delay_days ?? 0) }}" min="0" max="365">
                    <div class="form-text small">{{ __('admin/billing-rules.fields_delay_help') }}</div>
                </div>
            </div>
        </div>
    </x-admin.card>

    <x-admin.card id="conditionsSection">
        <h6 class="mb-3"><i class="fas fa-filter me-2"></i>{{ __('admin/billing-rules.conditions_section_title') }}</h6>

        {{-- Hidden JSON state, reactive UI manipulates it --}}
        <input type="hidden" name="conditions" id="conditionsJson"
               value="{{ json_encode(old('conditions', $rule?->conditions ?? ['type' => 'group', 'operator' => 'AND', 'children' => []])) }}">

        <div id="ruleBuilderRoot"></div>
        @error('conditions') <div class="text-danger small mt-1">{{ $message }}</div> @enderror

        <div id="overlapWarning"></div>

        <hr class="my-4">

        <h6 class="mb-3"><i class="fas fa-flask me-2"></i>{{ __('admin/billing-rules.test_section_title') }}</h6>
        <div class="row align-items-end">
            <div class="col-md-4">
                <label class="form-label">{{ __('admin/billing-rules.test_invoice_id_label') }}</label>
                <input type="number" id="testInvoiceId" class="form-control" min="1">
            </div>
            <div class="col-md-2">
                <button type="button" id="testBtn" class="btn btn-outline-secondary">{{ __('admin/billing-rules.test_button') }}</button>
            </div>
            <div class="col-md-6">
                <div id="testResult" class="form-text"></div>
            </div>
        </div>

        <x-slot:footer>
            <x-admin.form-actions :cancel-url="route('admin.billing.rules.index')" />
        </x-slot:footer>
    </x-admin.card>
</form>

@push('scripts')
<script>
window.ruleBuilderConfig = {
    fields: @json(collect($fields)->mapWithKeys(fn($f) => [$f => __('admin/billing-rules.fields_label_'.str_replace('.', '_', $f))])),
    operators: @json($operators),
    @if($isEdit)
    testRoute: "{{ route('admin.billing.rules.test', $rule) }}",
    @else
    testRoute: null,
    @endif
};
window.billingRuleFormConfig = {
    routes: {
        checkOverlap: '{{ route('api.admin.billing-rules.check-overlap') }}'
    },
    ruleId: {!! $isEdit ? $rule->id : 'null' !!},
    translations: {
        overlap_warning: '{{ __('admin/billing-rules.overlap_warning') }}',
        overlap_covered_by: '{{ addslashes(__('admin/billing-rules.overlap_covered_by')) }}'
    }
};
</script>
@vite('resources/js/admin/billing-rules/builder.js')
@vite('resources/js/admin/billing-rules/form.js')
@endpush
