import { Handlers, PageProps } from '$fresh/server.ts'
import { db, Todo, User, UserWithTodos } from '@homeman/models.ts'
import { TodoList } from '@homeman/components/TodoList.tsx'

const unassignedUserPlaceholder: User = {
	id: '',
	createdAt: new Date(),
	name: 'Shared',
	avatarUrl: 'http://placekitten.com/512/512',
	color: '888888',
}

interface Data {
	users: UserWithTodos[]
	unassignedTodos: Todo[]
}

export const handler: Handlers = {
	async GET(_req, ctx) {
		const users = await db.users.findMany({ include: { assignedTodos: true } })
		const unassignedTodos = await db.todos.findMany({
			where: { assigneeUserId: null },
		})
		return ctx.render({ users, unassignedTodos })
	},
}

export default function Home(
	{ data: { users, unassignedTodos } }: PageProps<Data>,
) {
	const unassignedUser: UserWithTodos = {
		...unassignedUserPlaceholder,
		assignedTodos: unassignedTodos,
	}
	return (
		<main class='flex flex-col'>
			<h1 class='p-5 border-b-2 border-stone-500/20 text-2xl'>
				Todos
			</h1>
			<ul class='p-4 relative flex'>
				<li>
					<TodoList user={unassignedUser} />
				</li>
				{users.map((u) => (
					<li>
						<TodoList user={u} />
					</li>
				))}
			</ul>
		</main>
	)
}
