@props([
    'name',
    'label' => null,
    'options' => [],
    'selected' => null,
    'placeholder' => null,
    'required' => false,
    'optional' => false,
    'lookup' => null,
    'lookupExclude' => null,
    'lookupParent' => null,
    'id' => null,
])

@php
    $id = $id ?? $name;
    $current = old($name, $selected);
    $errorBag = $errors ?? new \Illuminate\Support\ViewErrorBag();
    $hasError = $errorBag->has($name);
    $resolvedPlaceholder = $placeholder ?? __('common.select');
    $useAsync = filled($lookup);
    $lookupUrl = $useAsync ? route('lookups.search') : null;
@endphp

<x-ui.form.field
    :name="$name"
    :label="$label"
    :required="$required"
    :optional="$optional"
    :id="$id"
>
    <select
        id="{{ $id }}"
        name="{{ $name }}"
        @if ($required) required @endif
        data-erp-search-select
        @if ($useAsync)
            data-lookup-type="{{ $lookup }}"
            data-lookup-url="{{ $lookupUrl }}"
            @if ($lookupExclude) data-lookup-exclude="{{ $lookupExclude }}" @endif
            @if ($lookupParent) data-lookup-parent="{{ $lookupParent }}" @endif
        @endif
        data-placeholder="{{ $resolvedPlaceholder }}"
        {{ $attributes->merge(['class' => 'form-select erp-search-select'.($hasError ? ' is-invalid' : '')]) }}
    >
        <option value="">{{ $resolvedPlaceholder }}</option>

        @foreach ($options as $optValue => $optLabel)
            @if ((string) $optValue !== '')
                <option value="{{ $optValue }}" @selected((string) $current === (string) $optValue)>
                    {{ $optLabel }}
                </option>
            @endif
        @endforeach

        @if ($useAsync && filled($current) && ! array_key_exists((string) $current, $options))
            <option value="{{ $current }}" selected>
                {{ $options[$current] ?? $resolvedPlaceholder }}
            </option>
        @endif
    </select>
</x-ui.form.field>

@once
    @push('scripts')
        @php
            $erpSearchSelectI18n = [
                'searchPlaceholder' => __('common.search_select.search'),
                'noResults' => __('common.search_select.no_results'),
                'noChoices' => __('common.search_select.no_choices'),
                'typeToSearch' => __('common.search_select.type_to_search'),
                'loading' => __('common.search_select.loading'),
            ];
        @endphp
        <script>
            window.erpSearchSelectI18n = @json($erpSearchSelectI18n);
        </script>
        <script src="{{ asset('assets/admin/js/erp-search-select.js') }}?v={{ @filemtime(public_path('assets/admin/js/erp-search-select.js')) ?: '1' }}"></script>
    @endpush
@endonce
