import * as React from 'react'
import {__, _x} from '@wordpress/i18n'

import {
	useState,
} from '@wordpress/element'

import {
	BaseControl,
	Button,
} from '@wordpress/components'

import {
	useDispatch,
} from '@wordpress/data'

import {
	store as noticesStore,
} from '@wordpress/notices'

const NOTICE_ID = 'ska-inline-image-button'

const getImageType = (src: string) => {

	const url = new URL(src)
	const pathname = url.pathname

	let imageType = 'image/png'
	if(pathname.endsWith('.jpg') || pathname.endsWith('.jpeg')) {
		imageType = 'image/jpeg'
	} else if(pathname.endsWith('.gif')) {
		imageType = 'image/gif'
	} else if(pathname.endsWith('.webp')) {
		imageType = 'image/webp'
	}

	return imageType
}

export interface InlineImageButtonProps {
	src: string
	onClick: (dataURL: string) => void
}

/** Button that converts image from a URL to inlined data URL.  */
const InlineImageButton: React.FC<InlineImageButtonProps> = ({
	src,
	onClick,
}) => {

	const [loading, setLoading] = useState(false)

	const {
		createErrorNotice,
	} = useDispatch(noticesStore)

	return <>
		<BaseControl
			label={__('Inline image', 'ska-blocks')}
			help={__('Convert image URL to base64-encoded data URL, storing the whole image in post content.', 'ska-blocks')}
			__nextHasNoMarginBottom
		>
			<Button
				variant='primary'
				onClick={() => {

					setLoading(true)

					const img = new Image()
					img.crossOrigin = 'Anonymous'
					img.src = src

					const onLoad = () => {

						const canvas = document.createElement('canvas')
						const ctx = canvas.getContext('2d')
						if(!ctx) {
							createErrorNotice(__('Failed creating canvas context.', 'ska-blocks'), {id: NOTICE_ID})
							return
						}

						canvas.width = img.naturalWidth
						canvas.height = img.naturalHeight
						ctx.drawImage(img, 0, 0)

						const dataURL = canvas.toDataURL(getImageType(src))
						onClick(dataURL)
					}

					img.onerror = () => {
						createErrorNotice(
							__(`Failed loading image (most likely "No 'Access-Control-Allow-Origin' header is present on the requested resource.").`, 'ska-blocks'),
							{id: NOTICE_ID}
						)
					}

					img.onload = onLoad
					if(img.complete) {
						onLoad()
					}
				}}
				children={__('Convert', 'ska-blocks')}
				isBusy={loading}
				disabled={loading}
			/>
		</BaseControl>
	</>
}

export default InlineImageButton
