@extends('agency.layouts.app')

@section('title', 'Tanım Düzenle')

@section('page_title', $definition->definitionType->display_name . ' Düzenle')

@php
    $breadcrumbs = [
        ['title' => 'Dashboard', 'url' => route('agency.dashboard')],
        ['title' => 'Tanımlar', 'url' => route('agency.definitions.index')],
        ['title' => $definition->definitionType->display_name, 'url' => route('agency.definitions.index', ['type' => $definition->definition_type_id])],
        ['title' => 'Düzenle: ' . $definition->name, 'url' => '']
    ];
@endphp

@push('styles')
    <link href="https://cdn.jsdelivr.net/npm/quill@2.0.0/dist/quill.snow.css" rel="stylesheet">
    <style>
        .quill-editor {
            background: white;
            border-radius: var(--radius-lg);
        }

        .ql-toolbar.ql-snow {
            border-top-left-radius: var(--radius-lg);
            border-top-right-radius: var(--radius-lg);
            background: var(--gray-50);
            border: 1px solid var(--gray-300);
        }

        .ql-container.ql-snow {
            border-bottom-left-radius: var(--radius-lg);
            border-bottom-right-radius: var(--radius-lg);
            min-height: 200px;
            border: 1px solid var(--gray-300);
            border-top: 0;
        }

        .form-section {
            background: white;
            border-radius: var(--radius-xl);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid var(--gray-200);
        }

        .form-section-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid var(--gray-200);
        }

        .required-indicator {
            color: var(--danger-color);
            margin-left: 4px;
        }

        .field-description {
            font-size: 0.8rem;
            color: var(--gray-500);
            margin-top: 0.25rem;
        }

        .image-preview {
            width: 120px;
            height: 120px;
            border: 2px dashed var(--gray-300);
            border-radius: var(--radius-lg);
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--gray-50);
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .image-preview:hover {
            border-color: var(--primary-color);
            background: var(--primary-color) 05;
        }

        .image-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: var(--radius-md);
        }

        .image-preview-placeholder {
            text-align: center;
            color: var(--gray-400);
        }

        .current-image {
            position: relative;
            margin-bottom: 1rem;
        }

        .current-image img {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: var(--radius-lg);
            border: 1px solid var(--gray-200);
        }

        .remove-image {
            position: absolute;
            top: -8px;
            right: -8px;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background: var(--danger-color);
            color: white;
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            cursor: pointer;
        }

        .form-check-custom {
            background: var(--gray-50);
            border-radius: var(--radius-lg);
            padding: 1rem;
            transition: all 0.3s ease;
        }

        .form-check-custom:has(.form-check-input:checked) {
            background: var(--primary-color) 10;
            border: 1px solid var(--primary-color) 30;
        }

        .field-type-text, .field-type-textarea {
            background: var(--gray-50);
        }

        .field-type-number {
            background: var(--info-color) 05;
        }

        .field-type-select {
            background: var(--warning-color) 05;
        }

        .field-type-date {
            background: var(--success-color) 05;
        }

        .field-type-boolean {
            background: var(--secondary-color) 05;
        }

        .dynamic-attributes {
            border-top: 2px solid var(--gray-200);
            padding-top: 1.5rem;
            margin-top: 1.5rem;
        }

        .info-card {
            background: linear-gradient(135deg, var(--info-color) 10, var(--info-color) 05);
            border: 1px solid var(--info-color) 30;
            border-radius: var(--radius-lg);
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
    </style>
@endpush

@section('content')
    <div class="container-fluid">
        <!-- Info Card -->
        <div class="info-card">
            <div class="d-flex align-items-center">
                <i class="fas fa-info-circle text-info me-2"></i>
                <div>
                    <strong>{{ $definition->definitionType->display_name }} Düzenleniyor:</strong>
                    {{ $definition->name }}
                    <div class="small text-muted">
                        Oluşturulma: {{ $definition->created_at->format('d.m.Y H:i') }}
                        @if($definition->updated_at != $definition->created_at)
                            | Son güncelleme: {{ $definition->updated_at->format('d.m.Y H:i') }}
                        @endif
                    </div>
                </div>
                <div class="ms-auto">
                    <a href="{{ route('agency.definitions.show', $definition) }}" class="btn btn-outline-info btn-sm">
                        <i class="fas fa-eye me-1"></i>Görüntüle
                    </a>
                </div>
            </div>
        </div>

        <form method="POST" action="{{ route('agency.definitions.update', $definition) }}" enctype="multipart/form-data"
              class="validate-form">
            @csrf
            @method('PUT')

            <div class="row">
                <div class="col-lg-8">
                    <!-- Basic Information -->
                    <div class="form-section">
                        <h5 class="form-section-title">
                            <i class="{{ $definition->definitionType->icon ?? 'fas fa-info-circle' }} me-2"></i>
                            Temel Bilgiler
                        </h5>

                        <div class="row">
                            <div class="col-md-8">
                                <div class="mb-3">
                                    <label for="name" class="form-label">
                                        {{ $definition->definitionType->display_name }} Adı
                                        <span class="required-indicator">*</span>
                                    </label>
                                    <input type="text" class="form-control @error('name') is-invalid @enderror"
                                           id="name" name="name" value="{{ old('name', $definition->name) }}" required
                                           maxlength="255">
                                    @error('name')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="sort_order" class="form-label">Sıralama</label>
                                    <input type="number" class="form-control @error('sort_order') is-invalid @enderror"
                                           id="sort_order" name="sort_order"
                                           value="{{ old('sort_order', $definition->sort_order) }}" min="0">
                                    @error('sort_order')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="description" class="form-label">Açıklama</label>
                            <div class="quill-editor" id="editor-description"></div>
                            <input type="hidden" id="description" name="description" value="{{ old('description', $definition->description) }}">
                            @error('description')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <!-- Dynamic Attributes -->
                    @if($attributes->count() > 0)
                        <div class="form-section">
                            <h5 class="form-section-title">
                                <i class="fas fa-list-ul me-2"></i>
                                {{ $definition->definitionType->display_name }} Özellikleri
                            </h5>

                            <div class="dynamic-attributes">
                                <div class="row">
                                    @foreach($attributes as $attribute)
                                        @php
                                            $currentValue = $values[$attribute->name] ?? $attribute->default_value;
                                        @endphp
                                        <div
                                            class="col-md-{{ $attribute->field_type === 'textarea' ? '12' : '6' }} mb-3">
                                            <label for="attr_{{ $attribute->name }}" class="form-label">
                                                {{ $attribute->display_name }}
                                                @if($attribute->is_required)
                                                    <span class="required-indicator">*</span>
                                                @endif
                                            </label>

                                            @switch($attribute->field_type)
                                                @case('text')
                                                    <input type="text"
                                                           class="form-control field-type-text @error('attributes.'.$attribute->name) is-invalid @enderror"
                                                           id="attr_{{ $attribute->name }}"
                                                           name="attributes[{{ $attribute->name }}]"
                                                           value="{{ old('attributes.'.$attribute->name, $currentValue) }}"
                                                        {{ $attribute->is_required ? 'required' : '' }}>
                                                    @break

                                                @case('textarea')
                                                    @if($attribute->name === 'content')
                                                        <div class="quill-editor" id="editor_{{ $attribute->name }}"></div>
                                                        <input type="hidden"
                                                               id="attr_{{ $attribute->name }}"
                                                               name="attributes[{{ $attribute->name }}]"
                                                               value="{{ old('attributes.'.$attribute->name, $currentValue) }}"
                                                               {{ $attribute->is_required ? 'required' : '' }}>
                                                    @else
                                                        <textarea
                                                            class="form-control field-type-textarea @error('attributes.'.$attribute->name) is-invalid @enderror"
                                                            id="attr_{{ $attribute->name }}"
                                                            name="attributes[{{ $attribute->name }}]"
                                                            rows="3"
                                                              {{ $attribute->is_required ? 'required' : '' }}>{{ old('attributes.'.$attribute->name, $currentValue) }}</textarea>
                                                    @endif
                                                    @break

                                                @case('number')
                                                    <input type="number"
                                                           class="form-control field-type-number @error('attributes.'.$attribute->name) is-invalid @enderror"
                                                           id="attr_{{ $attribute->name }}"
                                                           name="attributes[{{ $attribute->name }}]"
                                                           value="{{ old('attributes.'.$attribute->name, $currentValue) }}"
                                                           @if($attribute->validation_rules)
                                                               @foreach($attribute->validation_rules as $rule => $value)
                                                                   @if($rule === 'min') min="{{ $value }}" @endif
                                                           @if($rule === 'max') max="{{ $value }}" @endif
                                                        @endforeach
                                                        @endif
                                                        {{ $attribute->is_required ? 'required' : '' }}>
                                                    @break

                                                @case('date')
                                                    <input type="date"
                                                           class="form-control field-type-date @error('attributes.'.$attribute->name) is-invalid @enderror"
                                                           id="attr_{{ $attribute->name }}"
                                                           name="attributes[{{ $attribute->name }}]"
                                                           value="{{ old('attributes.'.$attribute->name, $currentValue) }}"
                                                        {{ $attribute->is_required ? 'required' : '' }}>
                                                    @break

                                                @case('select')
                                                    <select
                                                        class="form-select field-type-select @error('attributes.'.$attribute->name) is-invalid @enderror"
                                                        id="attr_{{ $attribute->name }}"
                                                        name="attributes[{{ $attribute->name }}]"
                                                        {{ $attribute->is_required ? 'required' : '' }}>
                                                        <option value="">Seçiniz</option>
                                                        @if($attribute->options)
                                                            @foreach($attribute->options as $key => $value)
                                                                <option value="{{ $key }}"
                                                                    {{ old('attributes.'.$attribute->name, $currentValue) == $key ? 'selected' : '' }}>
                                                                    {{ $value }}
                                                                </option>
                                                            @endforeach
                                                        @endif
                                                    </select>
                                                    @break

                                                @case('boolean')
                                                    <div class="form-check-custom">
                                                        <div class="form-check">
                                                            <input
                                                                class="form-check-input @error('attributes.'.$attribute->name) is-invalid @enderror"
                                                                type="checkbox"
                                                                id="attr_{{ $attribute->name }}"
                                                                name="attributes[{{ $attribute->name }}]"
                                                                value="1"
                                                                {{ old('attributes.'.$attribute->name, $currentValue) ? 'checked' : '' }}>
                                                            <label class="form-check-label"
                                                                   for="attr_{{ $attribute->name }}">
                                                                Evet
                                                            </label>
                                                        </div>
                                                    </div>
                                                    @break
                                            @endswitch

                                            @if($attribute->description)
                                                <div class="field-description">{{ $attribute->description }}</div>
                                            @endif

                                            @error('attributes.'.$attribute->name)
                                            <div class="invalid-feedback d-block">{{ $message }}</div>
                                            @enderror
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    @endif
                </div>

                <div class="col-lg-4">
                    <!-- Image Upload -->
                    <div class="form-section">
                        <h5 class="form-section-title">
                            <i class="fas fa-image me-2"></i>
                            Görsel
                        </h5>

                        @if($definition->image)
                            <div class="current-image">
                                <img src="{{ asset('storage/' . $definition->image) }}" alt="Mevcut görsel">
                                <button type="button" class="remove-image" onclick="removeCurrentImage()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <div class="small text-muted mb-3">Mevcut görsel</div>
                        @endif

                        <div class="mb-3">
                            <label for="image" class="form-label">
                                {{ $definition->image ? 'Yeni Görsel Yükle' : ($definition->definitionType->display_name . ' Görseli') }}
                            </label>
                            <div class="image-preview" onclick="document.getElementById('image').click()">
                                <div class="image-preview-placeholder">
                                    <i class="fas fa-cloud-upload-alt fa-2x mb-2"></i>
                                    <div>{{ $definition->image ? 'Değiştir' : 'Görsel Yükle' }}</div>
                                    <small class="text-muted">JPG, PNG (Max: 2MB)</small>
                                </div>
                            </div>
                            <input type="file" class="form-control d-none @error('image') is-invalid @enderror"
                                   id="image" name="image" accept="image/*">
                            @error('image')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <!-- Status Settings -->
                    <div class="form-section">
                        <h5 class="form-section-title">
                            <i class="fas fa-cog me-2"></i>
                            Durum Ayarları
                        </h5>

                        <div class="mb-3">
                            <div class="form-check-custom">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="is_active" name="is_active"
                                           value="1"
                                        {{ old('is_active', $definition->is_active) ? 'checked' : '' }}>
                                    <label class="form-check-label" for="is_active">
                                        <strong>Aktif</strong>
                                        <div class="field-description">Bu tanım aktif olarak kullanılabilir</div>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <div class="form-check-custom">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="is_featured" name="is_featured"
                                           value="1"
                                        {{ old('is_featured', $definition->is_featured) ? 'checked' : '' }}>
                                    <label class="form-check-label" for="is_featured">
                                        <strong>Öne Çıkar</strong>
                                        <div class="field-description">Bu tanım öne çıkan tanımlar arasında gösterilir
                                        </div>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="form-section">
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>
                                Değişiklikleri Kaydet
                            </button>
                            <a href="{{ route('agency.definitions.show', $definition) }}" class="btn btn-outline-info">
                                <i class="fas fa-eye me-2"></i>
                                Görüntüle
                            </a>
                            <a href="{{ route('agency.definitions.index', ['type' => $definition->definition_type_id]) }}"
                               class="btn btn-outline-secondary">
                                <i class="fas fa-arrow-left me-2"></i>
                                Geri Dön
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
@endsection

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/quill@2.0.0/dist/quill.js"></script>
    <script>
        let currentImageRemoved = false;

        function removeCurrentImage() {
            if (confirm('Mevcut görseli kaldırmak istediğinize emin misiniz?')) {
                document.querySelector('.current-image').style.display = 'none';
                currentImageRemoved = true;

                // Add hidden input to indicate image removal
                let hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'remove_image';
                hiddenInput.value = '1';
                document.querySelector('form').appendChild(hiddenInput);
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            // Toolbar options for Quill
            const toolbarOptions = [
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'align': [] }],
                ['link'],
                ['clean']
            ];

            // Initialize Description Editor
            const descriptionEditorEl = document.getElementById('editor-description');
            if (descriptionEditorEl) {
                const descriptionEditor = new Quill('#editor-description', {
                    theme: 'snow',
                    modules: { toolbar: toolbarOptions },
                    placeholder: 'Açıklama yazın...'
                });

                const descriptionInput = document.getElementById('description');

                // Load initial value
                if (descriptionInput.value) {
                    descriptionEditor.root.innerHTML = descriptionInput.value;
                }

                // Update hidden input on change
                descriptionEditor.on('text-change', function() {
                    descriptionInput.value = descriptionEditor.root.innerHTML;
                });
            }

            // Initialize Content Attribute Editor
            const contentEditorEl = document.getElementById('editor_content');
            if (contentEditorEl) {
                const contentEditor = new Quill('#editor_content', {
                    theme: 'snow',
                    modules: { toolbar: toolbarOptions },
                    placeholder: 'İçeriği buraya yazın...'
                });

                const contentInput = document.getElementById('attr_content');

                // Load initial value
                if (contentInput.value) {
                    contentEditor.root.innerHTML = contentInput.value;
                }

                // Update hidden input on change
                contentEditor.on('text-change', function() {
                    contentInput.value = contentEditor.root.innerHTML;
                });
            }

            // Image preview
            const imageInput = document.getElementById('image');
            const imagePreview = document.querySelector('.image-preview');

            imageInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        imagePreview.innerHTML = `<img src="${e.target.result}" alt="Preview">`;
                    };
                    reader.readAsDataURL(file);
                }
            });

            // Form validation
            const form = document.querySelector('.validate-form');
            form.addEventListener('submit', function(e) {
                const requiredFields = form.querySelectorAll('[required]');
                let hasError = false;

                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        field.classList.add('is-invalid');
                        hasError = true;
                    } else {
                        field.classList.remove('is-invalid');
                    }
                });

                if (hasError) {
                    e.preventDefault();
                    AgencyPanel.showNotification('Lütfen tüm gerekli alanları doldurun.', 'warning');

                    // Scroll to first error
                    const firstError = form.querySelector('.is-invalid');
                    if (firstError) {
                        firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        firstError.focus();
                    }
                }
            });

            // Real-time validation
            const inputs = form.querySelectorAll('input, select, textarea');
            inputs.forEach(input => {
                input.addEventListener('blur', function() {
                    if (this.hasAttribute('required') && !this.value.trim()) {
                        this.classList.add('is-invalid');
                    } else {
                        this.classList.remove('is-invalid');
                    }
                });

                input.addEventListener('input', function() {
                    if (this.classList.contains('is-invalid') && this.value.trim()) {
                        this.classList.remove('is-invalid');
                    }
                });
            });

            // Number field validation
            const numberFields = form.querySelectorAll('input[type="number"]');
            numberFields.forEach(field => {
                field.addEventListener('input', function() {
                    const min = parseInt(this.getAttribute('min'));
                    const max = parseInt(this.getAttribute('max'));
                    const value = parseInt(this.value);

                    if (!isNaN(min) && value < min) {
                        this.setCustomValidity(`Minimum değer: ${min}`);
                    } else if (!isNaN(max) && value > max) {
                        this.setCustomValidity(`Maximum değer: ${max}`);
                    } else {
                        this.setCustomValidity('');
                    }
                });
            });

            // Auto-resize textareas
            const textareas = form.querySelectorAll('textarea');
            textareas.forEach(textarea => {
                textarea.addEventListener('input', function() {
                    this.style.height = 'auto';
                    this.style.height = this.scrollHeight + 'px';
                });

                // Initial resize
                textarea.style.height = 'auto';
                textarea.style.height = textarea.scrollHeight + 'px';
            });
        });
    </script>
@endpush
