import { DailyPhase, DailyPhaseModel, Task, toPhase } from '@homeman/models.ts'
import { useSignal } from '@preact/signals'
import { excitement } from '@homeman/common.ts'

export interface Props {
	tasks: Task[]
}

interface TaskWithIndex extends Task {
	index: number
}

const phaseEmoji: Record<DailyPhase, string> = {
	Morning: '🌄',
	Midday: '🌞',
	Evening: '🌆',
	Bedtime: '🛌',
	Night: '🌙',
}

type TaskGroups = Record<DailyPhase, TaskWithIndex[]>

export function Routine(
	props: Props,
) {
	const tasks = useSignal(props.tasks)
	const currentPhase = useSignal(toPhase())
	const taskGroups: TaskGroups = {
		Morning: [],
		Midday: [],
		Evening: [],
		Bedtime: [],
		Night: [],
	}
	tasks.value.forEach((t, i) => taskGroups[t.phase].push({ ...t, index: i }))
	return (
		<>
			<nav class='flex overflow-x-scroll'>
				{DailyPhaseModel.options.map((phase) => (
					<button
						onClick={() => {
							currentPhase.value = phase
							console.log(currentPhase, phase)
						}}
						class={`p-4 shrink-0 grow border-b-2 text-lg ${
							currentPhase.value == phase
								? 'border-purple-500'
								: 'border-gray-500/20 hover:border-gray-500'
						}`}
					>
						{phaseEmoji[phase]} {phase}
					</button>
				))}
			</nav>
			<main class='flex flex-col overflow-x-scroll'>
				<ul>
					{taskGroups[currentPhase.value].map((
						{ emoji, id, doneAt, index }: TaskWithIndex,
					) => (
						<li
							role='button'
							class={`text-lg cursor-pointer p-4 hover:bg-gray-500/20 ${
								doneAt ? 'line-through opacity-30 hover:bg-gray-500' : ''
							}`}
							onClick={() => {
								tasks.value[index].doneAt = tasks.value[index].doneAt
									? null
									: new Date()
								tasks.value = [...tasks.value]
								if (tasks.value[index].doneAt) {
									fetch('/api/tasks', {
										method: 'POST',
										headers: { 'content-type': 'application/json' },
										body: JSON.stringify({ id: id }),
									})
									excitement()
								} else {
									fetch('/api/tasks', {
										method: 'DELETE',
										headers: { 'content-type': 'application/json' },
										body: JSON.stringify({ id: id }),
									})
								}
							}}
						>
							{emoji ? `${emoji.trim()} ` : ''}
							{id.trim()}
						</li>
					))}
				</ul>
			</main>
		</>
	)
}
