export function editorImagePicker() {
    return {
        open: false,
        items: [],
        search: '',
        loading: false,
        uploading: false,
        page: 1,
        lastPage: 1,
        searchTimeout: null,
        selectedItem: null,
        captionText: '',
        showUploadForm: false,
        uploadCaption: '',

        init() {
            document.addEventListener('editor:open-picker', () => {
                this.open = true
                this.selectedItem = null
                this.captionText = ''
                this.showUploadForm = false
                this.uploadCaption = ''
                this.loadMedia(1)
            })
        },

        async loadMedia(page = 1) {
            this.loading = true
            this.page = page
            try {
                const params = new URLSearchParams({ type: 'image', page })
                if (this.search) params.set('search', this.search)
                const res = await fetch(`/admin/media/browse?${params}`)
                const data = await res.json()
                this.items = page === 1 ? (data.data ?? []) : [...this.items, ...(data.data ?? [])]
                this.lastPage = data.meta?.last_page ?? data.last_page ?? 1
            } finally {
                this.loading = false
            }
        },

        onSearchInput() {
            clearTimeout(this.searchTimeout)
            this.searchTimeout = setTimeout(() => this.loadMedia(1), 300)
        },

        selectItem(item) {
            this.selectedItem = item
            this.captionText = item.caption ?? ''
        },

        insert() {
            if (!this.selectedItem) return
            window._tiptapEditor?.commands.setImage({
                src: this.selectedItem.url,
                alt: this.captionText,
                title: this.captionText,
            })
            this.close()
        },

        close() {
            this.open = false
            this.search = ''
            this.items = []
            this.selectedItem = null
            this.captionText = ''
            this.showUploadForm = false
            this.uploadCaption = ''
        },

        async upload(event) {
            const file = event.target.files[0]
            if (!file) return
            this.uploading = true
            try {
                const form = new FormData()
                form.append('file', file)
                form.append('caption', this.uploadCaption)
                await fetch('/admin/media', {
                    method: 'POST',
                    headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
                    body: form,
                })
                event.target.value = ''
                this.uploadCaption = ''
                this.showUploadForm = false
                await this.loadMedia(1)
            } finally {
                this.uploading = false
            }
        },
    }
}
