import { nextTick, ref } from 'vue'
import { uploadImage } from '@/api/upload'
import type { PreviewImage, UploadedImage } from './types'

export function useInputImages(focusEditor: () => void) {
	const uploadedImages = ref<UploadedImage[]>([])
	const quoteList = ref<string[]>([])
	const showPreview = ref(false)
	const previewUrl = ref('')

	const handleFileChange = (event: Event) => {
		const input = event.target as HTMLInputElement

		if (input.files) {
			Array.from(input.files).forEach((file) => {
				if (file.type.startsWith('image/')) {
					const formData = new FormData()
					formData.append('file', file)

					uploadImage(formData).then((res) => {
						const reader = new FileReader()
						reader.onload = (e) => {
							uploadedImages.value.push({
								url: e.target?.result as string,
								name: file.name,
								path: res
							})
						}
						reader.readAsDataURL(file)
					})
				}
			})
		}

		nextTick(focusEditor)
		input.value = ''
	}

	const removeImage = (index: number, item: PreviewImage) => {
		if (typeof item === 'string') {
			const quoteIndex = quoteList.value.indexOf(item)
			if (quoteIndex > -1) {
				quoteList.value.splice(quoteIndex, 1)
			}
			return
		}

		uploadedImages.value.splice(index, 1)
	}

	const previewImage = (url: string) => {
		showPreview.value = true
		previewUrl.value = url
	}

	const handleQuote = (url: string) => {
		const hasQuoted = quoteList.value.includes(url)
		if (hasQuoted) return
		quoteList.value[0] = url
	}

	const clearImages = () => {
		uploadedImages.value = []
		quoteList.value = []
	}

	return {
		uploadedImages,
		quoteList,
		showPreview,
		previewUrl,
		handleFileChange,
		removeImage,
		previewImage,
		handleQuote,
		clearImages
	}
}
