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

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

interface Data {
	users: UserWithTodos[]
	allUsers: Record<string, User>
	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 },
		})
		const allUsers: Data['allUsers'] = {}
		for (const u of users) {
			allUsers[u.id] = u
		}
		return ctx.render({ users, unassignedTodos, allUsers })
	},
}

export default function Home(
	{ data: { users, unassignedTodos, allUsers } }: 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 overflow-x-scroll max-w-screen'>
				<li>
					<TodoList user={unassignedUser} users={allUsers} />
				</li>
				{users.map((u) => (
					<li>
						<TodoList user={u} users={allUsers} />
					</li>
				))}
			</ul>
		</main>
	)
}
