import { createRef } from 'preact'
import { type Signal, useSignal } from '@preact/signals'
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[]
}

async function promptDeleteUser(id: string, name: string) {
	if (confirm(`Are you sure you want to delete ${name} (${id})?`)) {
		await fetch(`/api/user?id=${id}`, { method: 'DELETE' })
		location.reload()
	}
}

export function Admin({ users, todos }: Props) {
	const editUser: Signal<User | null> = useSignal(null)
	const addUserDialog = createRef<HTMLDialogElement>()
	const editUserDialog = createRef<HTMLDialogElement>()
	const usersById: Record<string, User> = {}
	for (const u of users) {
		usersById[u.id] = u
	}
	return (
		<main class='flex flex-col'>
			<header class='flex items-center border-b-2 border-stone-500/20 '>
				<h1 class='p-5 text-2xl'>
					Administration Page
				</h1>
			</header>
			<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'
					encType='multipart/form-data'
					onSubmit={() => console.log('Submitting new user...')}
				>
					<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>
			<dialog
				class='rounded drop-shadow-lg backdrop:bg-stone-500/90'
				ref={editUserDialog}
			>
				<header class='p-4 flex w-full items-center border-b-2 border-stone-500/20'>
					<h1 class='text-xl grow'>{`Edit '${editUser.value?.name}'`}</h1>
					<Button
						onClick={() => editUserDialog.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'
					// TODO:
					// Form contains enctype=multipart/form-data, but does not contain method=post.
					// Submitting normally with method=GET and no enctype instead.
					// possible workaround? https://stackoverflow.com/questions/50691938/patch-and-put-request-does-not-working-with-form-data
					method='post'
					encType='multipart/form-data'
					onSubmit={() => console.log('Submitting edit user...')}
				>
					<Input type='hidden' name='_method' value='put' />
					<Input type='hidden' name='id' value={editUser.value?.id} />
					<Label for='name'>
						Name
						<Input autofocus name='name' value={editUser.value?.name} />
					</Label>
					<Label for='avatar'>
						Avatar
						<Input type='file' name='avatar' />
					</Label>
					<Label for='color'>
						Color
						<Input
							type='color'
							name='color'
							value={`#${editUser.value?.color}`}
						/>
					</Label>
					<footer class='flex justify-end gap-2'>
						<Button
							onClick={() => editUserDialog.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>
						<th>Actions</th>
					</tr>
				</thead>
				<tbody>
					{users.map((user) => {
						const { id, name, avatarUrl, color } = user
						return (
							<tr>
								<td>{name}</td>
								<td>
									{avatarUrl == null
										? 'None'
										: <img class='h-16 w-16 object-cover' src={avatarUrl} />}
								</td>
								<td style={`color: #${color}`}>
									#{color}
								</td>
								<td class=''>
									<Button
										title='Delete'
										className='py-2 mr-2'
										onClick={() => promptDeleteUser(id, name)}
									>
										<svg
											xmlns='http://www.w3.org/2000/svg'
											fill='none'
											viewBox='0 0 24 24'
											stroke-width='1.5'
											stroke='currentColor'
											class='w-6 h-6'
										>
											<path
												stroke-linecap='round'
												stroke-linejoin='round'
												d='m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0'
											/>
										</svg>
									</Button>
									<Button
										title='Edit'
										className='py-2'
										onClick={() => {
											editUser.value = user
											editUserDialog.current?.showModal()
										}}
									>
										<svg
											xmlns='http://www.w3.org/2000/svg'
											fill='none'
											viewBox='0 0 24 24'
											stroke-width='1.5'
											stroke='currentColor'
											class='w-6 h-6'
										>
											<path
												stroke-linecap='round'
												stroke-linejoin='round'
												d='m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10'
											/>
										</svg>
									</Button>
								</td>
							</tr>
						)
					})}
				</tbody>
			</table>
			<header class='flex items-center border-b-2 border-stone-500/20 '>
				<h1 class='p-5 text-2xl'>
					Todos ({todos.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>
	)
}
