import axios from 'axios'
import Sortable from 'sortablejs'

export function sliderEditor(existingSlides = []) {
    return {
        slides: existingSlides.map((s, i) => ({ ...s, _id: i, _open: false })),
        _counter: existingSlides.length,
        autoplay: true,
        interval: 5000,
        newSlide: { title: '', subtitle: '', image_url: '', image_alt: '', button_text: '', button_url: '', button_target: '_self' },
        saving: false,
        saveDone: false,
        saveMessage: '',

        // Media picker state
        pickerOpen: false,
        pickerCallback: null,
        pickerItems: [],
        pickerSearch: '',
        pickerLoading: false,
        pickerPage: 1,
        pickerLastPage: 1,
        pickerSearchTimer: null,
        pickerUploading: false,

        init() {
            this.$nextTick(() => this.initSortable())
        },

        initSortable() {
            const container = this.$refs.slidesList
            if (!container) return
            Sortable.create(container, {
                handle: '.drag-handle',
                animation: 150,
                ghostClass: 'opacity-40',
                onEnd: (evt) => {
                    const moved = this.slides.splice(evt.oldIndex, 1)[0]
                    this.slides.splice(evt.newIndex, 0, moved)
                },
            })
        },

        addSlide() {
            this.slides.push({
                ...this.newSlide,
                _id: ++this._counter,
                _open: false,
                is_active: true,
                sort_order: this.slides.length,
            })
            this.newSlide = { title: '', subtitle: '', image_url: '', image_alt: '', button_text: '', button_url: '', button_target: '_self' }
        },

        removeSlide(index) {
            this.slides.splice(index, 1)
        },

        // Media picker
        pickerSelected: null,

        openPicker(callback) {
            this.pickerCallback = callback
            this.pickerSearch = ''
            this.pickerPage = 1
            this.pickerSelected = null
            this.pickerOpen = true
            this.loadMedia()
        },

        closePicker() {
            this.pickerOpen = false
            this.pickerCallback = null
            this.pickerSelected = null
        },

        selectPickerItem(item) {
            this.pickerSelected = item
        },

        pickMedia(item) {
            if (this.pickerCallback) this.pickerCallback(item.url, item)
            this.closePicker()
        },

        async loadMedia(page = 1) {
            this.pickerLoading = true
            try {
                const { data } = await axios.get('/admin/media/browse', {
                    params: { search: this.pickerSearch, type: 'image', page },
                    headers: { Accept: 'application/json' },
                })
                this.pickerItems = data.data ?? []
                this.pickerPage = data.meta?.current_page ?? 1
                this.pickerLastPage = data.meta?.last_page ?? 1
            } catch {
                this.pickerItems = []
            } finally {
                this.pickerLoading = false
            }
        },

        onPickerSearch() {
            clearTimeout(this.pickerSearchTimer)
            this.pickerSearchTimer = setTimeout(() => this.loadMedia(1), 350)
        },

        async pickerUpload(event) {
            const file = event.target.files[0]
            if (!file) return
            this.pickerUploading = true
            const form = new FormData()
            form.append('file', file)
            try {
                await axios.post('/admin/media', form, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                await this.loadMedia(1)
            } catch (e) {
                const msg = e.response?.data?.message ?? e.response?.data ?? e.message ?? 'Upload failed.'
                alert('Upload error: ' + JSON.stringify(msg))
            } finally {
                this.pickerUploading = false
                event.target.value = ''
            }
        },

        async save(event) {
            const form = event.target
            this.saving = true
            this.saveMessage = ''
            this.saveDone = false

            const formData = new FormData(form)

            try {
                const { data } = await axios.post(form.action, formData, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                this.saveMessage = data.message ?? 'Slider saved.'
                this.saveDone = true
                setTimeout(() => { this.saveDone = false; this.saveMessage = '' }, 3000)
            } catch (e) {
                this.saveMessage = e.response?.data?.message ?? 'Error saving slider.'
                this.saveDone = false
            } finally {
                this.saving = false
            }
        },
    }
}

export function sliderForm() {
    return {
        saving: false,
        saved: false,
        message: '',

        async submit(event) {
            const form = event.target
            this.saving = true
            this.message = ''
            this.saved = false

            try {
                const { data } = await axios.post(form.action, new FormData(form), {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                this.saved = true
                this.message = data.message ?? 'Created.'
                if (data.redirect) window.location.href = data.redirect
            } catch (e) {
                this.message = e.response?.data?.message ?? 'Error creating slider.'
                this.saved = false
            } finally {
                this.saving = false
            }
        },
    }
}

export function slidersManager() {
    return {
        async deleteSlider(id) {
            if (!confirm('Delete this slider?')) return
            try {
                await axios.delete(`/admin/sliders/${id}`, {
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        Accept: 'application/json',
                    },
                })
                window.location.reload()
            } catch {
                alert('Error deleting slider.')
            }
        },
        init() {},
    }
}
