<template>
	<main v-if="userDetails.deleted">
		<h1>Deleted user {{ id }}</h1>
	</main>
	<main v-else>
		<h1>User {{ user.name }}</h1>
		<dl>
			<dt>
				<label for="user-type">
					Type
				</label>
			</dt>
			<dd>
				<select
					v-if='user.type !== "anonymous"'
					v-model="user.type"
				>
					<option value="regular">Regular</option>
					<option value="crew">Crew</option>
					<option value="admin">Admin</option>
				</select>
				<template v-else>
					{{ user.type }}
				</template>
			</dd>
			<dt>Interested Events:</dt>
			<dd>{{ userDetails.interestedEventIds }}</dd>
			<dt>Interested Slots:</dt>
			<dd>{{ userDetails.interestedEventSlotIds }}</dd>
			<dt>Timezone:</dt>
			<dd>{{ userDetails.timezone }}</dd>
			<dt>Locale:</dt>
			<dd>{{ userDetails.locale }}</dd>
		</dl>
		<button
			:disabled="!user.isModified()"
			type="button"
			@click="usersStore.saveUser(user);"
		>Save</button>
		<button
			:disabled="!user.isModified()"
			type="button"
			@click="user.discard()"
		>Discard</button>
	</main>
</template>

<script lang="ts" setup>
import type { ApiTombstone, ApiUserDetails } from '~/shared/types/api';

useHead({
	title: "Admin",
});

useEventSource();
const route = useRoute();
const usersStore = useUsersStore();
await usersStore.fetch();

const id = computed(() => {
	const id = queryToNumber(route.params.id);
	if (id === undefined) {
		throw createError({
			statusCode: 400,
			statusMessage: "Bad Request",
			message: "User id required",
		});
	}
	return id;
});
const user = computed(() => {
	const user =  usersStore.users.get(id.value);
	if (user === undefined) {
		throw createError({
			statusCode: 404,
			statusMessage: "Not Found",
			message: "User not found",
		});
	}
	return user;
});

const { pending, data, error } = await useFetch(() => `/api/users/${id.value}/details`);
const userDetails = data as Ref<ApiUserDetails | ApiTombstone>;
</script>

<style scoped>
dl {
	display: grid;
	grid-template-columns: auto 1fr;
	column-gap: 0.5rem;
}

</style>
