<script lang="ts">
	import { goto } from "@sapper/app";
	import { login } from "../../components/stores";
	import {
		getPlayerProfiles,
		getUUID,
		getUsername,
		putProfiles
	} from "../../lib/api";

	let username = "";
	let uuid = "";
	let status = "";
	let profilesPromise: ReturnType<typeof getPlayerProfiles> = new Promise(
		resolve => resolve([])
	);
</script>

<svelte:head>
	<title>Add Profile - Skyblock Data Tracker</title>
</svelte:head>

<div id="list">
	<form
		class="item"
		on:submit={async event => {
			event.preventDefault();
			try {
				profilesPromise = getPlayerProfiles(
					(uuid = await getUUID(username))
				);
			} catch (error) {
				status = "Not found";
			}
		}}
	>
		<h2>Add profile</h2>
		<p id="status">{status}</p>
		<input
			type="text"
			id="username"
			bind:value={username}
			placeholder="Minecraft Username"
		/>
		<input type="submit" value="Search" />
	</form>
	{#if uuid !== ""}
		{#await profilesPromise}
			<div class="item">
				<h2>Fetching profiles...</h2>
			</div>
		{:then profiles}
			{#each profiles as profile}
				<button
					type="button"
					class="item profile"
					on:click={async () => {
						try {
							await putProfiles(
								$login?.token,
								profile.profile_id,
								uuid
							);
						} catch (e) {
							if (
								e.response?.status === 401 ||
								e.response?.status === 403
							) {
								alert("Unauthorised");
							} else {
								alert(
									"An error occured while adding the profile"
								);
							}
						}
						goto("/#");
					}}
				>
					{#await getUsername(uuid)}
						<p>...</p>
					{:then properUsername}
						<p>{properUsername} @ {profile.cute_name}</p>
					{/await}
					{#each Object.keys(profile.members).filter(m => m !== uuid) as member}
						{#await getUsername(member)}
							<p>...</p>
						{:then memberUsername}
							<p>{memberUsername}</p>
						{:catch error}
							<p style="color: red">{error.message}</p>
						{/await}
					{/each}
				</button>
			{/each}
		{:catch error}
			<div class="item">
				<h2 style="color: red">{error.message}</h2>
			</div>
		{/await}
	{/if}
</div>

<style lang="scss">
	@use "../../styles/GridList";
	@use "../../styles/Form";

	.item {
		color: hsl(30, 20%, 90%);
	}
	form input[type="text"] {
		font-size: 1.17em;
		font-family: "Minecraft";
	}
	button.profile {
		font-size: 1.17em;
		font-family: "Minecraft";
		p:nth-child(1) {
			color: hsl(60, 100%, 50%);
			font-size: 2em;
		}
		&:hover {
			cursor: pointer;
		}
	}
</style>
