import { CancelIcon, FiltersIcon, PlusIcon, RefreshIcon } from '@/icons'
import { cn } from '@/utils/cn'
import { intervalToRange } from '@/utils/intervalToRange'
import { useState } from 'preact/hooks'
import { GRID_H_SNAP, GRID_WIDTH } from '../../constants'
import { useDashboardContext } from '../../contexts/DashboardContext'
import { DashboardFilters } from './components/DashboardFilters'
import { DashboardHeaderFilterToggle } from './components/DashboardHeaderFilterToggle'
import { DashboardSwitch } from './components/DashboardSwitch'

export const DashboardHeader = () => {
	const { verticalMode, boxes, setBoxes, setFilter } = useDashboardContext()
	const [filtersShown, setFiltersShown] = useState(false)

	const handleRefresh = () => {
		// @TODO: This is duplicate code, unify it somehow with dashboard filters
		setFilter((v) => {
			const range = intervalToRange(v.interval, v.customFrom, v.customTo)

			return {
				...v,
				customFrom: range[0],
				customTo: range[1],
			}
		})
	}

	const handleNewBox = () => {
		const box = {
			id: new Date().getTime().toString(),
			x: 0,
			y: 0,
			w: GRID_WIDTH,
			h: GRID_H_SNAP * 20,
		}

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

			return b
		})

		setBoxes(() => [box, ...otherBoxes])
	}

	return (
		<div className={cn('dashboard-head', verticalMode && 'vertical')}>
			{verticalMode && (
				<>
					<button className="icon" onClick={handleNewBox}>
						<PlusIcon />
					</button>
					<button className="icon" onClick={handleRefresh}>
						<RefreshIcon />
					</button>
					<div className="filter-button" onClick={() => setFiltersShown(true)}>
						<FiltersIcon />
					</div>

					<div
						className="filters-panel"
						style={{ right: !filtersShown ? '-20rem' : '0' }}
					>
						<div className="shadow" />
						<div className="inner">
							<div
								className="filter-close"
								onClick={() => setFiltersShown(false)}
							>
								<CancelIcon />
							</div>

							<DashboardSwitch />

							<DashboardFilters onClose={() => setFiltersShown(false)} />
						</div>
					</div>
					{filtersShown && (
						<div
							className="menu-overlay"
							onClick={() => setFiltersShown(false)}
						></div>
					)}
				</>
			)}
			{!verticalMode && (
				<>
					<DashboardSwitch />
					<button onClick={handleNewBox}>Add box</button>
					<DashboardHeaderFilterToggle />
					<button onClick={handleRefresh}>
						<RefreshIcon /> Refresh all
					</button>
				</>
			)}
		</div>
	)
}
