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

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

import {
	Modal,
	__experimentalView as View,
} from '@wordpress/components'

import {
	code,
} from '@wordpress/icons'

import {
	Pre,
	Button,
} from '@ska/components'

import {
	IS_DEBUG,
} from '@ska/utils'

export interface JsonViewProps {
	id?: string
	label?: string
	value: any
	/** @deprecated Use `size='small'`. */
	isSmall?: boolean
	size?: 'small' | 'default' | 'compact'
	right?: boolean
	variant?: 'link' | 'primary' | 'secondary'
	disabled?: boolean
	css?: boolean
	tabIndex?: number
	modalProps?: any
	renderFooter?: () => React.ReactNode
}

const JsonViewProd: React.FC<JsonViewProps> = () => null

const JsonViewDev: React.FC<JsonViewProps> = ({
	id = 'default',
	label = 'View raw data',
	value,
	isSmall = false,
	size: sizeValue,
	right = false,
	variant,
	disabled = false,
	css = false,
	tabIndex,
	modalProps = {},
	renderFooter,
}) => {

	const [isOpen, setIsOpen] = useState(false)
	const toggle = () => setIsOpen(!isOpen)
	const size = isSmall && !sizeValue ? 'small' : sizeValue

	useEffect(() => {
		if(isOpen) {
			// eslint-disable-next-line no-console
			console.debug(id, typeof value === 'function' ? value() : value)
		}
	}, [isOpen, id, value])

	return <>
		<Button
			variant={variant}
			size={size}
			icon={code}
			disabled={disabled || isOpen}
			label={label}
			onClick={toggle}
			tabIndex={tabIndex}
			style={{
				...(right && {float: 'right'}),
			}}
		/>
		{isOpen && (
			<Modal
				title={label}
				onRequestClose={() => setIsOpen(false)}
				{...modalProps}
			>
				<Pre
					css={css}
					value={typeof value === 'function' ? value() : value}
				/>
				{renderFooter && (
					<View style={{marginTop: 16}}>
						{renderFooter()}
					</View>
				)}
			</Modal>
		)}
	</>
}

const JsonView = IS_DEBUG ? JsonViewDev : JsonViewProd

/** JsonView that also renders in non-debug context. */
const UserJsonView = JsonViewDev
export {UserJsonView}

export default JsonView
