import {
	createDashboard,
	getDashboards,
	updateDashboard,
} 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 { DashboardGrid } from './components/DashboardGrid'
import { DashboardHeader } from './components/DashboardHeader'
import { DashboardContextProvider } from './contexts/DashboardContext'
import { BoxDefinition } from './types'

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]
	)

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

	const handleChange = (cb: (boxes: BoxDefinition[]) => BoxDefinition[]) => {
		const newBoxes = cb(boxes)

		setBoxes(newBoxes)

		if (dashboard && dashboardContent) {
			updateDashboard({
				id: dashboard?.id,
				contents: {
					...dashboardContent,
					boxes: newBoxes,
				},
			})
		}
	}

	const handleRefresh = () => {
		console.log('Nothing to refresh right now')
	}

	const handleNewBox = () => {
		const box = {
			id: new Date().getTime().toString(),
			x: 0,
			y: 0,
			w: 12,
			h: 200,
		}

		const otherBoxes = boxes.map((b) => {
			b.y += 200

			return b
		})

		setBoxes([box, ...otherBoxes])
		// TODO: Save
	}

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

	useEffect(() => {
		setBoxes(dashboardContent?.boxes ?? [])
	}, [dashboardContent])

	return (
		<DashboardContextProvider>
			<div className="dashboard">
				<DashboardHeader onRefresh={handleRefresh} onNewBox={handleNewBox} />
				<DashboardGrid boxes={boxes} onChange={handleChange} />
			</div>
		</DashboardContextProvider>
	)
}
