<script lang="ts" context="module">
	export type Token = {
		create_date: string;
		time_to_live: number;
		name: string;
	};
</script>

<script lang="ts">
	import { post, rdelete } from 'src/lib/requests.svelte';
	import { userStore } from 'src/routes/UserStore.svelte';

    import AddToken from './AddToken.svelte';

	let page = $state(0);
	let showNext = $state(false);
	let token_list: Token[] = $state([]);

	export async function getList() {
		if (!userStore.user) {
			return;
		}
		try {
			const res = await post('user/token/list', {
				id: userStore.user.id,
				page: page
			});
			token_list = res.token_list;
			showNext = res.show_next;
		} catch (e) {
			console.error('TODO notify user', e);
		}
	}

	async function removeToken(token: Token) {
		try {
			rdelete('user/token', { time: token.create_date });
			getList();
		} catch (e) {
			console.error('Notify the user', e);
		}
	}

	$effect(() => {
		if (userStore.user) {
			getList();
		}
	});
</script>

<div>
	<h2>Tokens</h2>
	<table>
		<thead>
			<tr>
				<th> Name </th>
				<th> Created </th>
				<th>
					<!-- Delete -->
				</th>
			</tr>
		</thead>
		<tbody>
			{#each token_list as token}
				<tr>
					<td>
						{token.name}
					</td>
					<td>
						{new Date(token.create_date).toLocaleString()}
					</td>
					<td>
						<button class="danger" on:click={() => removeToken(token)}>
							<span class="bi bi-trash"></span>
						</button>
					</td>
				</tr>
			{/each}
		</tbody>
	</table>
	<div class="flex justify-center align-center">
		<div class="grow-1 flex justify-end align-center">
			{#if page > 0}
				<button on:click={() => (page -= 1)}> Prev </button>
			{/if}
		</div>

		<div style="padding: 10px;">
			{page}
		</div>

		<div class="grow-1 flex justify-start align-center">
			{#if showNext}
				<button on:click={() => (page += 1)}> Next </button>
			{/if}
		</div>
	</div>
</div>

<AddToken on:reload={getList} />

<style lang="scss">
	.buttons {
		width: 100%;
		display: flex;
		justify-content: space-between;

		& > button {
			margin: 3px 5px;
		}
	}

	table {
		width: 100%;
		box-shadow: 0 2px 8px 1px #66666622;
		border-radius: 10px;
		border-collapse: collapse;
		overflow: hidden;
	}

	table thead {
		background: #60606022;
	}

	table tr td,
	table tr th {
		border-left: 1px solid #22222244;
		padding: 15px;
	}

	table tr td:first-child,
	table tr th:first-child {
		border-left: none;
	}

	table tr td button,
	table tr td .button {
		padding: 5px 10px;
		box-shadow: 0 2px 5px 1px #66666655;
	}
</style>
