import type { BaseBagelField } from '@bagelink/vue'
import type { ModalApi } from '../../../../../plugins/modal'

import type { EditorState } from '../richTextTypes'
import { bagelFormUtils as bglFrmUtil } from '@bagelink/vue'

export function insertImage(modal: ModalApi, state: EditorState) {
	const { range, doc } = state
	if (!range || !doc) return

	modal.showModalForm<{
		src: string
		alt: string
		width: number
		height: number
		figcaption: boolean
	}>({
		title: 'Upload Image',
		schema: [
			{ id: 'src', $el: 'file', attrs: { bindkey: 'url' } },
			{ id: 'alt', $el: 'text', label: 'Alt Text' },
			bglFrmUtil.frmRow(
				bglFrmUtil.numField('width', 'Width', { min: 1 }),
				bglFrmUtil.numField('height', 'Height', { min: 1 }),
			),
			{ id: 'figcaption', $el: 'check', label: 'Show Caption' },
		],
		onSubmit: (data: { [key: string]: any }) => {
			if (data.src) {
				const img = doc.createElement('img')
				Object.assign(img, {
					src: data.src,
					alt: data.alt || '',
					width: data.width || undefined,
					height: data.height || undefined
				})

				const node = data.figcaption
					? (() => {
						const figcaption = doc.createElement('figcaption')
						figcaption.textContent = data.alt
						const figure = doc.createElement('figure')
						figure.append(img, figcaption)
						return figure
					})()
					: img

				range.collapse(false)
				range.insertNode(node)
				state.content = doc.body.innerHTML
			}
		}
	})
}

export function insertLink(modal: ModalApi, state: EditorState) {
	const { range, doc } = state
	if (!range || !doc) return

	modal.showModalForm({
		title: 'Insert Link',
		schema: [
			{ id: 'url', $el: 'text', label: 'URL' },
			{ id: 'openInNewTab', $el: 'check', label: 'Open in new tab' },
		],
		onSubmit: (data: { url: string, openInNewTab: boolean }) => {
			if (data.url) {
				const anchor = doc.createElement('a')
				anchor.href = data.url
				if (data.openInNewTab) anchor.target = '_blank'
				range.surroundContents(anchor)
				state.content = doc.body.innerHTML
			}
		}
	})
}

export interface InsertImbedModalData { url: string, width?: number, height?: number, allowFullscreen?: boolean }

export function insertEmbed(modal: ModalApi, state: EditorState) {
	const { range, doc } = state
	if (!range || !doc) return

	modal.showModalForm<InsertImbedModalData
	>({
		title: 'Insert Embed',
		schema: [
			{ id: 'url', $el: 'text', label: 'URL', attrs: { placeholder: 'Enter URL (YouTube, Vimeo, etc.)' } },
			bglFrmUtil.frmRow(
				bglFrmUtil.numField('width', 'Width', { min: 200, placeholder: '560' }),
				bglFrmUtil.numField('height', 'Height', { min: 200, placeholder: '315' })
			),
			{ id: 'allowFullscreen', $el: 'check', label: 'Allow Fullscreen', value: true } as BaseBagelField<InsertImbedModalData, 'allowFullscreen'>,
		],
		onSubmit: (data: { url: string, width?: number, height?: number, allowFullscreen?: boolean }) => {
			if (!data.url) return

			// Convert common video URLs to embed URLs
			const url = new URL(data.url)
			let embedUrl = data.url

			// YouTube
			if (url.hostname.includes('youtube.com') || url.hostname === 'youtu.be') {
				const videoId = url.hostname === 'youtu.be'
					? url.pathname.slice(1)
					: url.searchParams.get('v')
				if (videoId) {
					embedUrl = `https://www.youtube.com/embed/${videoId}`
				}
			}
			// Vimeo
			else if (url.hostname.includes('vimeo.com')) {
				const videoId = url.pathname.split('/').pop()
				if (videoId) {
					embedUrl = `https://player.vimeo.com/video/${videoId}`
				}
			}

			const iframe = doc.createElement('iframe')
			Object.assign(iframe, {
				src: embedUrl,
				width: data.width || 560,
				height: data.height || 315,
				frameBorder: '0',
				allow: 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture',
				allowFullscreen: data.allowFullscreen
			})

			// Create a wrapper div for proper alignment and spacing
			const wrapper = doc.createElement('div')
			wrapper.style.textAlign = 'center'
			wrapper.style.margin = '1em 0'
			wrapper.appendChild(iframe)

			range.deleteContents()
			range.insertNode(wrapper)
			state.content = doc.body.innerHTML
		}
	})
}
