import * as React from 'react'

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

import {
	__experimentalVStack as VStack,
	__experimentalView as View,
	Button,
	CheckboxControl,
} from '@wordpress/components'

import {
	ImportExportStringsContext,
} from '@ska/components'

import {
	EXPORTABLES,
} from './util'

import {
	useImports,
} from './hooks'

export interface AutoImporterProps {
	valueToImport: any
}

const AutoImporter: React.FC<AutoImporterProps> = ({valueToImport}) => {

	const {
		importedLabel,
		importAllLabel,
		createMissingEntitiesLabel,
		createMissingEntitiesDescription,
		summaryLabel,
	} = useContext(ImportExportStringsContext)

	const [createEntities, setCreateEntities] = useState(true)
	const [importing, setImporting] = useState(false)
	const [isDone, setIsDone] = useState(false)
	const [imports, onImport] = useImports(valueToImport, {createEntities})

	const IMPORTABLES = EXPORTABLES.filter(({value}) => value in imports)

	return (
		<View className='ska__import-export__auto-importer'>
			<VStack alignment='start' spacing={6}>
				<Button
					className='ska__import-export__auto-importer__import-button'
					variant='primary'
					children={isDone ? importedLabel : importAllLabel}
					isBusy={importing}
					disabled={isDone}
					onClick={async () => {
						setImporting(true)
						await onImport()
						setImporting(false)
						setIsDone(true)
					}}
				/>
				<CheckboxControl
					label={createMissingEntitiesLabel}
					help={createMissingEntitiesDescription}
					checked={createEntities}
					onChange={() => setCreateEntities(!createEntities)}
					__nextHasNoMarginBottom
				/>
				{!isDone && (
					<View>
						<p><strong>{summaryLabel}</strong></p>
						<ul>
							{IMPORTABLES.map(({label, value}) => {
								const contents = imports[value]
								return contents.length > 0 ? (
									<li key={value}>
										{label} <code className='ska-code'>{contents.length}</code>
										<ul>
											{contents.map(({slug, label}) => {
												return (
													<li key={`${value}-${slug}`}>
														{label} <code className='ska-code'>{slug}</code>
													</li>
												)
											})}
										</ul>
									</li>
								) : null
							})}
						</ul>
					</View>
				)}
			</VStack>
		</View>
	)
}

export default AutoImporter
