<script setup>
import { ref, watch } from 'vue'
import { router } from '@inertiajs/vue3'
import { PencilSquareIcon, CheckIcon, XMarkIcon } from '@heroicons/vue/24/outline'

const props = defineProps({
    // Label gösterimi için
    label: { type: String, default: '' },
    // Mevcut değer
    modelValue: { type: [String, Number, null], default: null },
    // Inertia patch URL'i
    patchUrl: { type: String, required: true },
    // Form field adı (örn: 'email', 'admin_notes')
    field: { type: String, required: true },
    // Input tipi
    type: { type: String, default: 'text' },  // text | email | url | textarea
    // Placeholder
    placeholder: { type: String, default: '' },
    // Boş bırakılabilir mi
    nullable: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'saved'])

const editing = ref(false)
const inputValue = ref(props.modelValue ?? '')
const saving = ref(false)
const error = ref(null)

watch(() => props.modelValue, (v) => { inputValue.value = v ?? '' })

function startEdit() {
    inputValue.value = props.modelValue ?? ''
    editing.value = true
    error.value = null
}

function cancel() {
    editing.value = false
    inputValue.value = props.modelValue ?? ''
    error.value = null
}

function save() {
    if (saving.value) return
    if (!props.nullable && !inputValue.value?.toString().trim()) {
        error.value = 'Bu alan boş olamaz'
        return
    }
    saving.value = true
    error.value = null

    router.patch(props.patchUrl, { [props.field]: inputValue.value }, {
        preserveScroll: true,
        preserveState: true,
        onSuccess: () => {
            emit('update:modelValue', inputValue.value)
            emit('saved', inputValue.value)
            editing.value = false
            saving.value = false
            window.$toast?.success(props.label ? `${props.label} güncellendi` : 'Güncellendi')
        },
        onError: (errors) => {
            error.value = errors?.[props.field] || 'Kaydetme başarısız'
            saving.value = false
        },
    })
}

function onKeydown(e) {
    if (e.key === 'Enter' && props.type !== 'textarea') {
        e.preventDefault()
        save()
    } else if (e.key === 'Escape') {
        e.preventDefault()
        cancel()
    }
}
</script>

<template>
    <div class="group relative">
        <!-- View mode -->
        <div v-if="!editing" class="flex items-center gap-2">
            <span class="text-sm text-slate-900 dark:text-slate-100">
                <slot :value="modelValue">{{ modelValue || '—' }}</slot>
            </span>
            <button
                @click="startEdit"
                class="opacity-0 group-hover:opacity-100 rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-indigo-600 transition dark:hover:bg-slate-700"
                title="Düzenle"
            >
                <PencilSquareIcon class="h-3.5 w-3.5" />
            </button>
        </div>

        <!-- Edit mode -->
        <div v-else class="space-y-2">
            <textarea
                v-if="type === 'textarea'"
                v-model="inputValue"
                :placeholder="placeholder"
                rows="3"
                class="w-full rounded-lg border border-indigo-300 bg-white dark:bg-slate-800 dark:border-indigo-600 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                @keydown="onKeydown"
            />
            <input
                v-else
                v-model="inputValue"
                :type="type"
                :placeholder="placeholder"
                class="w-full rounded-lg border border-indigo-300 bg-white dark:bg-slate-800 dark:border-indigo-600 px-3 py-2 text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
                @keydown="onKeydown"
                autofocus
            />

            <p v-if="error" class="text-xs text-red-600">{{ error }}</p>

            <div class="flex items-center gap-2">
                <button
                    @click="save"
                    :disabled="saving"
                    class="inline-flex items-center gap-1 rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-emerald-700 disabled:opacity-50"
                >
                    <CheckIcon class="h-3.5 w-3.5" />
                    {{ saving ? 'Kaydediliyor...' : 'Kaydet' }}
                </button>
                <button
                    @click="cancel"
                    class="inline-flex items-center gap-1 rounded-lg border border-slate-300 bg-white dark:border-slate-600 dark:bg-slate-800 px-3 py-1.5 text-xs font-medium text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-700"
                >
                    <XMarkIcon class="h-3.5 w-3.5" /> İptal
                </button>
                <span class="text-[10px] text-slate-400">
                    {{ type === 'textarea' ? 'Ctrl+Enter ile kaydet' : 'Enter ile kaydet · Esc iptal' }}
                </span>
            </div>
        </div>
    </div>
</template>
