import type { EntityID } from '@wovin/core/applog'
import type { Accessor, Component, Setter } from 'solid-js'
import type { RelationModelDef } from '../data/Relations'
import { useLocation, useNavigate } from '@solidjs/router'
import { Logger } from 'besonders-logger'
import { createReaction, createSignal } from 'solid-js'
import { useAgent } from '../data/agent/AgentState'
import { copyToClipboard } from '../data/block-ui-helpers-paste'
import { removeBlockRelAndMaybeDelete } from '../data/block-utils'
import { relVMtest } from '../data/VMs/RelationVM'
import { useCurrentThread } from '../ui/reactive'
import { focusViewOnBlock, makeNote3Url } from '../ui/utils-ui'
import { Iconify } from './mini-components'

const { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.INFO, { prefix: '[RadialMenu]' }) // eslint-disable-line unused-imports/no-unused-vars

export let active: Accessor<boolean>, setRadialActive: Setter<boolean>
export interface Position {
	screenX: number
	screenY: number
}
export let pos: Accessor<Position>, setRadialPos: Setter<Position>
let radialRef
export let traceSet

export const RadialMenu: Component<{
	blockID?: EntityID
	relation?: RelationModelDef
	parentRelation?: RelationModelDef
}> = function RadialMenu(props) {
	// if (!blockID) return null
	const { onCopyID, onCopyLink, onFocus, onDelete } = handlersForRadialMenu(blockID, relation, parentRelation)
	;[active, setRadialActive] = createSignal(false)
	;[pos, setRadialPos] = createSignal({ screenX: 150, screenY: 150 })

	// const anchor = createMemo(() => ({
	const anchor = {
		getBoundingClientRect() {
			LOG('inGetAnchor', pos())
			return {
				width: 0,
				height: 0,
				x: pos()?.screenX ?? 0,
				y: pos()?.screenY ?? 0,
				top: pos()?.screenY ?? 0,
				left: pos()?.screenX ?? 0,
				right: pos()?.screenX ?? 0,
				bottom: pos()?.screenY ?? 0,
			}
		},
	}
	traceSet = ({ screenX, screenY }: Position, blockID: EntityID, relationID: EntityID) => {
		// blkVMtest(blockID)
		relVMtest(relationID)
		VERBOSE('pos before', pos())
		setRadialPos({ screenX, screenY })
		DEBUG('set', radialRef, pos(), { screenX, screenY })
		// radialRef.anchor = anchor()
		radialRef.reposition()
		setRadialActive(true)
		setTimeout(() => setRadialActive(false), 2000)
	}

	createReaction(() => LOG('reaction', anchor, pos()))
	// let radialElem
	// onMountFx(() => {
	// 	if (!radialElem) {
	// 		WARN('[EditableContent] contentElem is not set', radialElem, { blockVM })
	// 		setTimeout(() => {
	// 			if (radialElem) WARN('It was a timing issue!', radialElem, { blockVM }) // probably not, but worth a shot.
	// 		}, 1000)
	// 		return
	// 	}
	// 	interact(radialElem)
	// 		.on('doubletap', function(event) {
	// 			LOG('double')
	// 		})
	// 	radialElem.addEventListener('click', stopPropagation, true)
	// 	// true to use capturing
	// 	radialElem.addEventListener('keydown', keydownListener, true) // true to use capturing
	// 	// make sure to clean up when the component is unmounted
	// })()
	// onCleanup(() => {
	// 	radialElem.removeEventListener('keydown', keydownListener, true)
	// 	radialElem.removeEventListener('click', stopPropagation, true) // true to use capturing
	// })
	const MenuLayout = () => (
		<>
			<Iconify name='dot-duotone' />
			<div class='circle' />
			<style>
				{`
					.popup-virtual-element sl-popup::part(popup) {
						z-index: 1000;
						pointer-events: none;
					}

					.popup-virtual-element .circle {
						width: 100px;
						height: 100px;
						position: relative;
						top: -12px;
						left: 4px;
						border: solid 4px var(--sl-color-primary-600);
						border-radius: 50%;
						translate: -50px -50px;
						animation: 1s virtual-cursor infinite;
					}

				`}
			</style>
		</>
	)
	return (
		<div class='popup-virtual-element'>
			<sl-popup placement='right-start' ref={radialRef} active={active()} {...{ anchor }}>
				<MenuLayout />
			</sl-popup>
		</div>
	)
}

function handlersForRadialMenu(blockID, relation: RelationModelDef, parentRelation: RelationModelDef) {
	const currentDS = useCurrentThread()
	const location = useLocation()
	const navigator = useNavigate()

	// VERBOSE({ setAsof })
	const onCopyID = (evt: MouseEvent) => copyToClipboard(blockID)
	const onCopyLink = (evt: MouseEvent) => {
		const pub = useAgent().w3NamePublic // TODO: smart-select pub & UX for other cases
		// const n3url = `note3://publication/${pub}/?focus=${blockID}`
		const n3url = makeNote3Url({ pub, block: blockID })
		DEBUG('Note3 url', n3url)
		copyToClipboard(n3url)
	}
	const onFocus = (evt: MouseEvent) => focusViewOnBlock({ id: blockID }, { location, navigate: navigator }) //
	const onDelete = (evt: MouseEvent) => removeBlockRelAndMaybeDelete(currentDS, blockID, relation)

	return { onCopyLink, onCopyID, onFocus, onDelete }
}
