<template>
	<table>
		<thead>
			<tr>
				<th>Id</th>
				<th>Name</th>
				<th>Type</th>
				<th>Last Update</th>
				<th></th>
			</tr>
		</thead>
		<tbody>
			<tr v-for="user in usersStore.users.values()">
				<td>{{ user.id }}</td>
				<td>
					{{ user.name }}
				</td>
				<td>
					<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>
				</td>
				<td>
					{{ user.updatedAt.toFormat("yyyy-LL-dd HH:mm") }}
				</td>
				<td>
					<button
						v-if="user.isModified()"
						type="button"
						@click="saveUser(user);"
					>Save</button>
					<button
						v-if="user.isModified()"
						type="button"
						@click="user.discard()"
					>Discard</button>
				</td>
			</tr>
		</tbody>
	</table>
</template>

<script lang="ts" setup>
import { DateTime } from 'luxon';

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

async function saveUser(user: ClientUser) {
	try {
		await $fetch("/api/admin/user", {
			method: "PATCH",
			body: user.toApi(),
		});
	} catch (err: any) {
		console.error(err);
		alert(err?.data?.message ?? err.message);
	}
}
</script>

<style>

</style>
