import { useDebounceFn } from '@vueuse/core'
import { router } from '@inertiajs/vue3'
import { ref } from 'vue'

/**
 * Auto-Save Composable
 *
 * Text-Eingaben: Debounce 500ms vor dem Speichern
 * Selects/Checkboxen: Sofortige Speicherung (kein Debounce)
 *
 * @param {string} url - Die URL zum Speichern
 * @param {string} method - HTTP-Methode ('put' oder 'post')
 * @returns {{ save: Function, saveImmediate: Function, saving: Ref<boolean>, saved: Ref<boolean> }}
 */
export function useAutoSave(url, method = 'put') {
    const saving = ref(false)
    const saved = ref(false)
    let savedTimeout = null

    const performSave = (data) => {
        saving.value = true
        saved.value = false

        router[method](url, data, {
            preserveScroll: true,
            preserveState: true,
            onSuccess: () => {
                saving.value = false
                saved.value = true

                if (savedTimeout) clearTimeout(savedTimeout)
                savedTimeout = setTimeout(() => {
                    saved.value = false
                }, 2000)
            },
            onError: () => {
                saving.value = false
            },
        })
    }

    // Text-Eingaben: 500ms Debounce
    const save = useDebounceFn((data) => {
        performSave(data)
    }, 500)

    // Selects/Checkboxen: Sofort speichern
    const saveImmediate = (data) => {
        save.cancel()
        performSave(data)
    }

    return { save, saveImmediate, saving, saved }
}
