@props([
    'name',
    'label' => '',
    'id' => null,
    'options' => [],
    'value' => [],
    'col' => 3,
    'required' => null,
    'relation' => 'name',
    'ajax_url' => null,
    'ajax_params' => 'q',
    'ajax_extra_params' => [],
])

@php
    $fieldId = $id ?? $name;

    $selectedValues = collect($value)->map(function ($item) use ($relation) {
        if (is_object($item)) {
            return [
                'id' => $item->id,
                'text' => $item->name
                    ?? $item->title
                    ?? $item->text
                    ?? ($item->{$relation} ?? '')
            ];
        }

        return [
            'id' => $item,
            'text' => $item
        ];
    });
@endphp

<div class="col-md-{{ $col }}">
    <label for="{{ $fieldId }}" class="form-label">
        {{ $label }}
        @if($required)
            <span class="text-danger">*</span>
        @endif
    </label>

    <select
        name="{{ $name }}[]"
        id="{{ $fieldId }}"
        class="form-select form-select-sm select2"
        multiple
    >
        @foreach ($options as $key => $text)
            <option
                value="{{ $key }}"
                {{ in_array($key, $selectedValues->pluck('id')->toArray()) ? 'selected' : '' }}
            >
                {{ $text }}
            </option>
        @endforeach
    </select>

    {{-- Validation --}}
    @error($name)
        <span class="text-danger">
            <small>{{ $message }}</small>
        </span>
    @enderror
</div>

@if ($ajax_url)
    <script>
        document.addEventListener("DOMContentLoaded", function () {

            let extraParams = @json($ajax_extra_params);
            let selected = @json($selectedValues);

            let select = $('#{{ $fieldId }}').select2({
                placeholder: "{{ __('dashboard.select') }} {{ $label }}",
                allowClear: true,
                ajax: {
                    url: "{{ $ajax_url }}",
                    dataType: "json",
                    delay: 300,
                    data: function (params) {
                        let extra = {};
                        Object.keys(extraParams).forEach(key => {
                            extra[key] = $(extraParams[key]).val();
                        });

                        return {
                            "{{ $ajax_params }}": params.term,
                            ...extra
                        };
                    },
                    processResults: function (data) {
                        return {
                            results: data
                        };
                    }
                }
            });

            // preload selected values (edit mode)
            selected.forEach(item => {
                let option = new Option(item.text, item.id, true, true);
                select.append(option);
            });

            select.trigger('change');
        });
    </script>
@endif
