<script lang="ts">
	import { onMount } from 'svelte';
	import { get, showMessage } from '$lib/requests.svelte';
	import { notificationStore } from 'src/lib/NotificationsStore.svelte';
	import Spinner from 'src/lib/Spinner.svelte';

	let list = $state<
		| {
				name: string;
				id: string;
		  }[]
		| undefined
	>(undefined);

	onMount(async () => {
		try {
			list = await get('models');
		} catch (e) {
			showMessage(e, notificationStore, 'Could not request list of models');
		}
	});
</script>

<svelte:head>
	<title>Models</title>
</svelte:head>

<main>
	{#if list}
		{#if list.length > 0}
			<div class="list-header">
				<h2>My Models</h2>
				<div class="expand"></div>
				<a class="button" href="/models/add"> New </a>
			</div>
			<table class="table">
				<thead>
					<tr>
						<th> Name </th>
						<th>
							<!-- Open Button -->
						</th>
					</tr>
				</thead>
				<tbody>
					{#each list as item}
						<tr>
							<td>
								{item.name}
							</td>
							<td class="text-center">
								<a class="button simple" href="/models/edit?id={item.id}"> Edit </a>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		{:else}
			<h2 class="text-center">You don't have any models</h2>
			<div class="text-center">
				<a class="button padded" href="/models/add"> Create a new model </a>
			</div>
		{/if}
	{:else}
		<div style="text-align: center;">
			<Spinner />
		</div>
	{/if}
</main>

<style lang="scss">
	main {
		padding: 20px 15vw;
	}
	.list-header {
		display: flex;
		padding-bottom: 10px;
	}

	.list-header h2 {
		margin: 0;
		padding: 10px 5px;
	}

	.list-header .expand {
		flex-grow: 1;
	}

	.list-header .button,
	.list-header button {
		padding: 10px 10px;
		height: calc(100% - 20px);
		margin-top: 5px;
	}
</style>
