<div>
    <form enctype="multipart/form-data">
        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="dikkan_figure">Dikkan Figure *</label>
            <div class="col-sm-10">
                <input class="form-control" id="dikkan_figure" type="text" wire:model.live="dikkan_figure" autocomplete="off">
                <div>
                    @error('dikkan_figure')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        @foreach($this->taxonomies as $tax)
            <div class="row mb-3">
                <label class="col-sm-2 col-form-label" for="category">{{ $tax->name }}</label>
                <div class="col-sm-10">
                    <select class="form-control" wire:model="selectedTaxonomies.{{ $tax->id }}">
                        <option value="">Seçiniz...</option>

                        @if ($tax->children->isNotEmpty())
                            {!! $this->renderCategoryOptions($tax) !!}
                        @endif

                    </select>
                    <div>
                        @error('category')
                            <span class="error">{{ $message }}</span>
                        @enderror
                    </div>
                </div>
            </div>
        @endforeach

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="impa_code">Impa Code</label>
            <div class="col-sm-10">
                <input class="form-control" id="impa_code" type="text" wire:model.live="impa_code" autocomplete="off">
                <div>
                    @error('impa_code')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="category">Ikonlar</label>
            <div class="col-sm-10">
                <select class="form-control" multiple wire:model.live="icons_id">
                    <option value="">Seçiniz...</option>
                    @foreach ($this->icons as $icon)
                        <option value="{{ $icon->id }}">{{ $icon->name }}</option>
                    @endforeach
                </select>
                <div>
                    @error('icons')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="mb-3">
            <x-file-manager id="fm1" name="image" title="Görsel" :path="$image_path" />
        </div>
        <div class="mb-3">
            <x-file-manager id="fm2" name="td_image" title="TD Görsel" :path="$td_image_path" />
        </div>
        <div class="mb-3">
            <x-file-manager id="fm3" name="datasheet" title="Data Sheet" :path="$datasheet_path" />
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="title">3D Model (*.glb)</label>
            <div class="col-sm-10">
                <input type="file" wire:model.live="glb_file_path" id="glb_file_path" name="glb_file_path" class="form-control" accept=".glb">
                <div>
                    @error('title')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-12 col-form-label" for="youtube_video_id">Youtube Video ID <i>(Örn: https://www.youtube.com/watch?v=<b>dM3ohqKs2aQ</b> sadece kalın yazan kısım)</i></label>
            <div class="col-sm-12">
                <input class="form-control" id="youtube_video_id" type="text" wire:model="youtube_video_id" autocomplete="off">
                <div>
                    @error('youtube_video_id')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <hr/>

        <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 0; margin: 0 0 30px 0;">
            <h3 class="text-primary">Görseller</h3>
            <button class="btn btn-primary text-white" type="button" id="lfm1" data-path="path-lfm1" data-preview="holder-lfm1" style="height: 5rem;"> Dosya <br/> Yöneticisi </button>
        </div>

        <div id="inputs-container">
            <div class="row">
                @foreach($inputs as $index => $input)
                    <div class="col-lg-3 mb-4">
                        <div style="display: flex; justify-content: center;">
                            <div style="display: flex; flex-direction: column; justify-content: center;  text-align: center; gap: 10px;">
                                <div>
                                    {{-- <label for="image{{ $index }}">Görsel {{ $index + 1 }}</label> --}}
                                    <input type="hidden" wire:model="inputs.{{ $index }}.fileName" id="image{{ $index }}" class="form-control" value="{{ $input['fileName'] }}" readonly>
                                    <input type="hidden" wire:model="inputs.{{ $index }}.filePath" name="image_paths[]" value="{{ $input['filePath'] }}">
                                    <img src="{{ $input['filePath'] }}" style="width: 200px;  height: 200px; object-fit: contain;"/>
                                </div>
                                <div>
                                    <input class="form-control" wire:model="inputs.{{ $index }}.title" type="text" autocomplete="off" placeholder="başlık / grup adı" style="text-align: center;">
                                </div>
                            </div>
                            <span>
                                <a href="javascript:void(0)" wire:click.prevent="removeInput({{ $index }})">
                                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width:24px; color: var(--cui-link-color);">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                                    </svg>
                                </a>
                            </span>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>

        <hr/>

        <div style="display: flex; justify-content: end; align-items: center; gap: 10px; margin-bottom: 10px;">
            Düzenlenen diller:
            @foreach ($languages as $language)
                <a href="#" wire:click.prevent="changeLanguage('{{ $language->short }}')"
                    wire:key="lang-{{ $language->id }}"
                    class="btn btn-sm {{ $selectedLanguage == $language->short ? 'btn-primary' : 'btn-outline-primary' }}">
                    {{ strtoupper($language->short) }}
                </a>
            @endforeach
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="title">Başlık</label>
            <div class="col-sm-10">
                <input class="form-control" id="title" type="text" wire:model.live="title" autocomplete="off">
                <div>
                    @error('title')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="slug">Slug *</label>
            <div class="col-sm-10">
                <div class="input-group mb-3"><span class="input-group-text" id="basic-addon3">{{ url('/') }}/</span>
                    <input class="form-control" id="slug" type="text" wire:model.live="slug" autocomplete="off">
                </div>
                <div>
                    @error('slug')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="technical_features">Technical Features</label>
            <div class="col-sm-10">
                <div wire:ignore>
                    <textarea wire:model="technical_features" class="form-control" name="technical_features" id="technical_features"></textarea>
                </div>
                <div>
                    @error('technical_features')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="pressure_temperature_ranges">Pressure & Temperature Ranges</label>
            <div class="col-sm-10">
                <div wire:ignore>
                    <textarea wire:model="pressure_temperature_ranges" class="form-control" name="pressure_temperature_ranges" id="pressure_temperature_ranges"></textarea>
                </div>
                <div>
                    @error('pressure_temperature_ranges')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="material_specs">Material Specifications</label>
            <div class="col-sm-10">
                <div wire:ignore>
                    <textarea wire:model="material_specs" class="form-control" name="material_specs" id="material_specs"></textarea>
                </div>
                <div>
                    @error('material_specs')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="figure_options">Figure Options</label>
            <div class="col-sm-10">
                <div wire:ignore>
                    <textarea wire:model="figure_options" class="form-control" name="figure_options" id="figure_options"></textarea>
                </div>
                <div>
                    @error('figure_options')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <div class="row mb-3">
            <label class="col-sm-2 col-form-label" for="dimensions">Dimensions</label>
            <div class="col-sm-10">
                <div wire:ignore>
                    <textarea wire:model="dimensions" class="form-control" name="dimensions" id="dimensions"></textarea>
                </div>
                <div>
                    @error('dimensions')
                        <span class="error">{{ $message }}</span>
                    @enderror
                </div>
            </div>
        </div>

        <hr/>
        <div style="display:flex; justify-content: space-between;">
            <h4>Varyasyonlar</h4>
            <button wire:click.prevent="addVariantInput" class="btn btn-primary">+</button>
        </div>
        @foreach ($variantInputs as $index => $variantInput)
            <div class="row mb-3">
                @foreach ($variantInput as $key => $value)
                    <div class="col">
                        <input class="form-control" type="text" wire:model="variantInputs.{{ $index }}.{{ $key }}" placeholder="{{ ucfirst(str_replace('_', ' ', $key)) }}">
                    </div>
                @endforeach
                <div class="col">
                    @if(count($variantInputs) > 1)
                        <button wire:click.prevent="removeVariantInput({{ $index }})" class="btn btn-danger text-white">-</button>
                    @endif
                </div>
            </div>
        @endforeach

        @if ($errors->any())
            <div class="alert alert-danger">
                <ul style="margin-bottom:0 !important;">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <button class="btn btn-primary" type="submit" wire:click.prevent="saveAndRedirect" wire:loading.attr="disabled" wire:target="save, saveAndRedirect">Kaydet</button>
        <button class="btn btn-primary" type="submit" wire:click.prevent="save" wire:loading.attr="disabled" wire:target="save, saveAndRedirect">Kaydet ve Eklemeye Devam Et</button>

    </form>

</div>

@push('js')
    <script>
        class MyUploadAdapter {
            constructor(loader) {
                this.loader = loader;
            }

            upload() {
                return this.loader.file
                    .then(file => new Promise((resolve, reject) => {
                        this._initRequest();
                        this._initListeners(resolve, reject, file);
                        this._sendRequest(file);
                    }));
            }

            abort() {
                if (this.xhr) {
                    this.xhr.abort();
                }
            }

            _initRequest() {
                const xhr = this.xhr = new XMLHttpRequest();
                xhr.open('POST', '{{ route('admin.pages.ckeditor-upload') }}', true);
                xhr.setRequestHeader('X-CSRF-TOKEN', '{{ csrf_token() }}');
                xhr.responseType = 'json';
            }

            _initListeners(resolve, reject, file) {
                const xhr = this.xhr;
                const loader = this.loader;
                const genericErrorText = `Couldn't upload file: ${file.name}.`;

                xhr.addEventListener('error', () => reject(genericErrorText));
                xhr.addEventListener('abort', () => reject());
                xhr.addEventListener('load', () => {
                    const response = xhr.response;

                    if (!response || response.error) {
                        return reject(response && response.error ? response.error.message : genericErrorText);
                    }

                    resolve({
                        default: response.url
                    });
                });

                if (xhr.upload) {
                    xhr.upload.addEventListener('progress', evt => {
                        if (evt.lengthComputable) {
                            loader.uploadTotal = evt.total;
                            loader.uploaded = evt.loaded;
                        }
                    });
                }
            }

            _sendRequest(file) {
                const data = new FormData();
                data.append('upload', file);
                this.xhr.send(data);
            }
        }

        function MyCustomUploadAdapterPlugin(editor) {
            editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
                return new MyUploadAdapter(loader);
            };
        }
    </script>

<script>
    function initCKEditor(selector, propertyName) {
        ClassicEditor
            .create(document.querySelector(selector), {
                removePlugins: ['Title'],
                extraPlugins: [MyCustomUploadAdapterPlugin],
                height: 250,
            })
            .then(editor => {
                editor.editing.view.change(writer => {
                    writer.setStyle('height', '250px', editor.editing.view.document.getRoot());
                });

                editor.model.document.on('change:data', () => {
                    @this.set(propertyName, editor.getData());
                });

                Livewire.on('languageChanged', function(event) {
                    editor.setData(event[propertyName]);
                });
            })
            .catch(error => {
                console.error(error);
            });
    }

    function initCKEditors() {
        initCKEditor('#technical_features', 'technical_features');
        initCKEditor('#pressure_temperature_ranges', 'pressure_temperature_ranges');
        initCKEditor('#material_specs', 'material_specs');
        initCKEditor('#figure_options', 'figure_options');
        initCKEditor('#dimensions', 'dimensions');
    }
</script>
@endpush