import { createDashboard, getDashboards } from '@/api/dashboards'
import { createDashboardContent } from '@/utils/createDashboardContent'
import { parseDashboard } from '@/utils/parseDashboard'
import { useEffect, useMemo, useState } from 'preact/hooks'
import { useQuery } from 'react-query'
import { EditableBox } from './components/EditableBox'
import { normalizeBoxes } from './utils/normalizeBoxes'

export const NewDashboardPage = () => {
	const dashboards = useQuery(['/dashboards'], getDashboards)
	const dashboard = dashboards.data?.find((i) => i.id === 'default')

	const dashboardContent = useMemo(
		() => (dashboard ? parseDashboard(dashboard.contents) : undefined),
		[dashboard]
	)

	// Terrible code - ensure there's default dashboard
	useEffect(() => {
		if (dashboards.data && !dashboard) {
			createDashboard({
				id: 'default',
				contents: createDashboardContent(),
			}).then(() => {
				dashboards.refetch()
			})
		}
	}, [dashboards.data, dashboard])

	const [boxes, setBoxes] = useState(dashboardContent?.boxes ?? [])

	return (
		<div className="grid-sensors">
			{boxes.map((b) => (
				<EditableBox
					box={b}
					key={b.id}
					boxes={boxes}
					onPosition={(p) => {
						setBoxes((previous) => {
							b.x = p.x
							b.y = p.y

							return normalizeBoxes([...previous])
						})
					}}
					onResize={(s) => {
						setBoxes((previous) => {
							b.w = s.w
							b.h = s.h

							return normalizeBoxes([...previous])
						})
					}}
				/>
			))}
		</div>
	)
}
