import { BlockPreview } from '@wordpress/block-editor'
import { rawHandler } from '@wordpress/blocks'
import { useEffect, useState, useRef, useMemo } from '@wordpress/element'
import { __, sprintf } from '@wordpress/i18n'
import classNames from 'classnames'
import { Templates as TemplatesApi } from '@extendify/api/Templates'
import { useIsDevMode } from '@extendify/hooks/helpers'
import { AuthorizationCheck, Middleware } from '@extendify/middleware'
import { useGlobalStore } from '@extendify/state/GlobalState'
import { useUserStore } from '@extendify/state/User'
import { injectTemplateBlocks } from '@extendify/util/templateInjection'
import { DevButtonOverlay } from './DevHelpers'
import { NoImportModal } from './modals/NoImportModal'
import { ProModal } from './modals/ProModal'
const canImportMiddleware = Middleware([
'hasRequiredPlugins',
'hasPluginsActivated',
])
export function ImportTemplateBlock({ template, maxHeight }) {
const importButtonRef = useRef(null)
const once = useRef(false)
const hasAvailableImports = useUserStore(
(state) => state.hasAvailableImports,
)
const loggedIn = useUserStore((state) => state.apiKey.length)
const setOpen = useGlobalStore((state) => state.setOpen)
const pushModal = useGlobalStore((state) => state.pushModal)
const removeAllModals = useGlobalStore((state) => state.removeAllModals)
const blocks = useMemo(
() => rawHandler({ HTML: template.fields.code }),
[template.fields.code],
)
const [loaded, setLoaded] = useState(false)
const devMode = useIsDevMode()
const [topValue, setTopValue] = useState(0)
const focusTrapInnerBlocks = () => {
if (once.current) return
once.current = true
Array.from(
importButtonRef.current.querySelectorAll(
'a, button, input, textarea, select, details, [tabindex]:not([tabindex="-1"])',
),
).forEach((el) => el.setAttribute('tabIndex', '-1'))
}
const importTemplates = async () => {
await canImportMiddleware.check(template)
AuthorizationCheck(canImportMiddleware)
.then(() => {
setTimeout(() => {
injectTemplateBlocks(blocks, template)
.then(() => removeAllModals())
.then(() => setOpen(false))
.then(() => canImportMiddleware.reset())
}, 100)
})
.catch(() => {})
}
const handleKeyDown = (event) => {
if (['Enter', 'Space', ' '].includes(event.key)) {
event.stopPropagation()
event.preventDefault()
importTemplate()
}
}
const importTemplate = () => {
// Make a note that they attempted to import
TemplatesApi.maybeImport(template)
if (template?.fields?.pro && !loggedIn) {
pushModal(