import { createRef } from 'preact'
import { Todo, User } from '@homeman/models.ts'
import { Button } from '@homeman/components/Button.tsx'
import { Input } from '@homeman/components/Input.tsx'
import { Label } from '@homeman/components/Label.tsx'

export interface Props {
	users: User[]
	todos: Todo[]
}

export function Admin({ users, todos }: Props) {
	const addUserDialog = createRef<HTMLDialogElement>()
	const usersById: Record<string, User> = {}
	for (const u of users) {
		usersById[u.id] = u
	}
	return (
		<main class='flex flex-col'>
			<dialog
				class='rounded drop-shadow-lg backdrop:bg-stone-500/90'
				ref={addUserDialog}
			>
				<header class='p-4 flex w-full items-center border-b-2 border-stone-500/20'>
					<h1 class='text-xl grow'>Add user</h1>
					<Button
						onClick={() => addUserDialog.current?.close()}
						class='text-xl p-4 border-b-2 mr-4'
					>
						✕
					</Button>
				</header>
				<form class='p-4 gap-4 flex flex-col' action='/api/user' method='post'>
					<Label for='name'>
						Name
						<Input autofocus name='name' />
					</Label>
					<Label for='avatar'>
						Avatar
						<Input type='file' name='avatar' />
					</Label>
					<Label for='color'>
						Color
						<Input type='color' name='color' />
					</Label>
					<footer class='flex justify-end gap-2'>
						<Button
							onClick={() => addUserDialog.current?.close()}
						>
							Cancel
						</Button>
						<Input type='submit' value='Save' />
					</footer>
				</form>
			</dialog>
			<header class='flex items-center border-b-2 border-stone-500/20 '>
				<h1 class='p-5 text-2xl'>
					Users ({users.length})
				</h1>
				<Button onClick={() => addUserDialog.current?.showModal()}>
					Add User
				</Button>
			</header>
			<table class='border-separate [border-spacing:1.25rem] text-left'>
				<thead>
					<tr>
						<th>Name</th>
						<th>Avatar</th>
						<th>Color</th>
					</tr>
				</thead>
				<tbody>
					{users.map(({ name, avatarUrl, color }) => (
						<tr>
							<td>{name}</td>
							<td>
								{avatarUrl == null
									? 'None'
									: <img class='h-16 w-16' src={avatarUrl} />}
							</td>
							<td style={`color: #${color}`}>
								#{color}
							</td>
						</tr>
					))}
				</tbody>
			</table>
			<header class='flex items-center border-b-2 border-stone-500/20 '>
				<h1 class='p-5 text-2xl'>
					Todos ({users.length})
				</h1>
				<Button>+</Button>
			</header>
			<table class='border-separate [border-spacing:1.25rem] text-left'>
				<thead>
					<tr>
						<th>Description</th>
						<th>Assignee</th>
					</tr>
				</thead>
				<tbody>
					{todos.map(({ description, assigneeUserId }) => (
						<tr>
							<td>{description}</td>
							<td>
								{assigneeUserId == null
									? 'Unassigned'
									: usersById[assigneeUserId]?.name}
							</td>
						</tr>
					))}
				</tbody>
			</table>
		</main>
	)
}
