<script lang="ts">
	import { onMount } from 'svelte';
	import { isSignInRedirect, getProviderFromUrl } from '@lit-protocol/lit-auth-client';
	import type { IRelayPKP } from '@lit-protocol/types';
	// import { ProviderType } from '@lit-protocol/constants';
	import Icon from '@iconify/svelte';
	import { createLitSession } from '$lib/services/createLitSession/createLitSession';
	import Apps from '$lib/components/Apps.svelte';
	import { connectProvider } from '$lib/services/provider/setupLit';

	const redirectUri = 'http://localhost:5173/';

	let sessionSigs, error, currentPKP, authMethod, provider;
	let log = '';
	let pkps: IRelayPKP[] = [];
	let view = 'SIGN_IN';

	onMount(() => {
		initialize();
	});

	async function initialize() {
		addToLog('Initialization...');
		try {
			provider = await connectProvider();
			addToLog('Connected to Google provider.');
			if (isSignInRedirect(redirectUri)) {
				const providerName = getProviderFromUrl();
				if (providerName) {
					await handleRedirect(providerName);
				}
			}
		} catch (err) {
			setError(err);
		}
	}

	async function authWithGoogle() {
		try {
			if (!provider) {
				provider = await connectProvider();
				addToLog('Reconnected to Google provider.');
			}
			await provider.signIn();
			addToLog('Signed in with Google.');
		} catch (err) {
			setError(err);
		}
	}

	async function handleRedirect(providerName: string) {
		try {
			if (!provider) throw new Error('Invalid provider.');
			authMethod = await provider.authenticate();
			addToLog('Authenticated successfully.');
			pkps = await provider.fetchPKPsThroughRelayer(authMethod);
			addToLog('Fetched PKPs.');
			if (pkps.length === 0) {
				addToLog('No PKPs found. Minting...');
				await mint();
			} else {
				// Update the view to 'PKP' to show the available PKPs
				view = 'PKP';
			}
		} catch (err) {
			setError(err);
		}
	}

	async function mint() {
		const newPKP: IRelayPKP = await mintPkp(provider, authMethod);
		pkps = [...pkps, newPKP];
		addToLog('New PKP minted.');
		await createSession(newPKP);
	}

	async function createSession(pkp: IRelayPKP) {
		try {
			currentPKP = pkp; // Assign the selected PKP to currentPKP
			sessionSigs = await createLitSession(provider, pkp.publicKey, authMethod);
			addToLog('Session created successfully.');
			view = 'READY';
		} catch (err) {
			setError(err);
		}
	}

	function setError(err) {
		error = err;
		view = 'ERROR';
		addToLog(`Error: ${err.message}`);
	}

	function addToLog(message: string) {
		log += `${message}\n`;
	}
</script>

<div class="flex items-center justify-center h-screen">
	<div>
		{#if error}
			<div class="mt-4 text-center">
				<h1>Error</h1>
				<p>{error.message}</p>
			</div>
		{:else if view === 'SIGN_IN'}
			<button on:click={authWithGoogle} class="btn variant-filled">
				<span><Icon icon="flat-color-icons:google" /></span>
				<span>Sign in with Google</span>
			</button>
		{:else if view === 'PKP'}
			<div>
				<h1>Select a PKP to continue</h1>
				{#each pkps as pkp}
					<button on:click={() => createSession(pkp)}>{pkp.ethAddress}</button>
				{/each}
			</div>
		{:else if view === 'READY'}
			<div>
				<h1>Ready for the open web</h1>
				<p>Check out your PKP:</p>
				<p>{currentPKP.ethAddress}</p>
				<Apps />
			</div>
		{/if}
		<pre class="mt-4">{log}</pre>
	</div>
</div>
