import React, { Suspense, useState } from 'react'
import { ControlPanel } from './ControlPanel'
import { AdminBar } from './AdminBar'
import { MapplicStore } from '../../mapplic/src/MapplicStore'
import '../../mapplic/src/mapplic.css'
import './mapplic-admin.css'
import { UploadFieldContextProvider } from './UploadFieldContext'

const MapplicElement = React.lazy(() => import('../../mapplic/src/MapplicElement'));

const MapplicAdmin = ({json = 'data.json', action, saveMap, title, uploadField, state}) => {
	return (
		<MapplicStore>
			<UploadFieldContextProvider value={uploadField}>
				<AdminBuilder json={json} action={action} saveMap={saveMap} title={title} state={state} />
			</UploadFieldContextProvider>
		</MapplicStore>
	)
}

const AdminBuilder = ({json, action, saveMap, title, state = 1}) => {
	const [view, setView] = useState('desktop');
	const [history, setHistory] = useState(0);

	const updateHistory = (step = true) => setHistory((prev) => step ? Math.abs(prev) + 1 : -Math.abs(prev) - 1);

	return (
		<div className="mapplic-admin">
			<ControlPanel updateHistory={updateHistory} action={action} title={title} state={state} />
			<div className="mapplic-admin-main">
				<AdminBar history={history} view={view} setView={setView} saveMap={saveMap} />
				<div className="mapplic-admin-content">
					<div id="map-container" className={view}>
						<Suspense fallback={<div>Loading...</div>}>
							<MapplicElement json={json} />
						</Suspense>
					</div>
				</div>
			</div>
		</div>
	)
}

export default MapplicAdmin