import { Budget } from '../models.ts'
import { BudgetCard, ProgressBarCard } from './BudgetCard.tsx'
import { Currency } from '../components/Currency.tsx'
import { Nav } from '../islands/Nav.tsx'
import { IS_BROWSER } from '$fresh/runtime.ts'
import { useCallback, useEffect } from 'preact/hooks'
import { useSignal } from '@preact/signals'

const budgets: Budget[] = [
	{
		name: 'Groceries',
		target: 1000,
		spent: 367.97,
	},
	{
		name:
			'A very long budget name that should definitely be shortened to something reasonable',
		target: 100000000,
		spent: 26893085.56,
	},
	{
		name: 'Fast Food',
		target: 300,
		spent: 420.69,
	},
	{
		name: 'Insurance',
		target: 220.44,
		spent: 0,
	},
	{
		name: 'Mortgage',
		target: 1310.47,
		spent: 1310.47,
	},
]

export function BudgetsOverview() {
	let sig = useSignal(IS_BROWSER ? globalThis.location.hash : '')

	addEventListener('popstate', (ev) => {
		console.log('popstate', ev)
		sig.value = globalThis.location.hash
		ev.preventDefault()
		return false
	})

	useEffect(() => {
		setTimeout(() => {
			console.log('Timeout!')
		}, 2000)
		addEventListener('popstate', (ev) => {
			console.log('popstate', ev)
			sig.value = globalThis.location.hash
		})
	}, [sig])

	const uncategorizedSpend = 851.22

	return (
		<div class='h-[100vh] flex flex-col max-w-full'>
			<header class='bg-mantle'>
				<h1 class='text-2xl font-mono p-2 px-2'>FlanBank</h1>
				{sig.value}
			</header>
			<section class='grid grid-rows-[1fr_auto] sm:grid-cols-2 sm:grid-rows-1 sm:grid-cols-[1fr_auto] flex-1 max-w-full max-w-2xl mx-auto'>
				<main class='p-2 sm:pr-0 flex flex-col gap-2 max-w-full' f-client-nav>
					{/*<h1>Budgets Overview</h1>*/}
					<section class='flex flex-col gap-2 max-w-full'>
						{uncategorizedSpend <= 0 ? '' : (
							<ProgressBarCard
								heading='Uncategorized'
								bgClass='bg-yellow opacity-20'
								accentTextClass='text-yellow'
								fillRatio={1.0}
								subheading={
									<>
										<Currency amount={uncategorizedSpend} />
									</>
								}
							>
								<small>You should categorize these!</small>
							</ProgressBarCard>
						)}
						{budgets.map((budget, _i) => <BudgetCard budget={budget} />)}
					</section>
				</main>
				<Nav />
			</section>
		</div>
	)
}
