<script lang="ts">
	import { goto } from '$app/navigation';
	import { parseInviteCode } from '$lib/invites';

	window.eve.listCCNs().then((ccns) => {
		if (ccns.length > 0) return goto('/');
	});

	let mode = $state<'initial' | 'join' | 'create'>('initial');
	let inviteCode = $state('');
	let ccnName = $state('');
	let ccnDescription = $state('');

	let isValidInviteCode = $derived(checkInviteCode(inviteCode));

	function checkInviteCode(inviteCode: string): boolean {
		try {
			let parsed = parseInviteCode(inviteCode as `${string}1${string}`);
			if (parsed) return true;
			return false;
		} catch {
			return false;
		}
	}

	function joinCCN() {
		mode = 'join';
		inviteCode = '';
	}

	function createCCN() {
		mode = 'create';
		ccnName = '';
		ccnDescription = '';
	}

	async function handleJoinSubmit() {
		if (inviteCode.trim()) {
			const parsed = parseInviteCode(inviteCode as `${string}1${string}`);
			if (parsed) {
				await window.eve.joinCCN(
					parsed.version,
					parsed.startIndex,
					parsed.name,
					parsed.description,
					parsed.key
				);
				window.location.reload();
			}
		}
	}

	async function handleCreateCCN() {
		if (ccnName.trim() && ccnDescription.trim()) {
			try {
				await window.eve.createCCN(ccnName.trim(), ccnDescription.trim());
				window.location.reload();
			} catch (error) {
				console.error('Failed to create CCN:', error);
			}
		}
	}

	function goBack() {
		mode = 'initial';
	}
</script>

<div class="flex h-full w-full items-center justify-center">
	<div class="w-96">
		{#if mode === 'initial'}
			<div class="text-center p-4">
				<h3 class="font-bold text-lg mb-4">Welcome to Eve</h3>
				<p class="text-gray-600 mb-6">Join an existing CCN or create a new one</p>

				<div class="space-y-3">
					<button class="btn btn-primary btn-block" onclick={joinCCN}>
						Join with Invite Code
					</button>

					<button class="btn btn-secondary btn-block" onclick={createCCN}> Create New CCN </button>
				</div>
			</div>
		{:else if mode === 'join'}
			<div class="p-4">
				<div class="flex items-center mb-4">
					<button class="btn btn-sm btn-ghost mr-2" onclick={goBack}>←</button>
					<h3 class="font-bold text-lg">Join CCN</h3>
				</div>

				<form onsubmit={handleJoinSubmit} class="space-y-4">
					<div class="form-control w-full">
						<label class="label" for="invite-code">
							<span class="label-text">Invite Code</span>
						</label>
						<input
							id="invite-code"
							type="text"
							placeholder="Enter invite code..."
							class="input input-bordered w-full"
							bind:value={inviteCode}
							required
						/>
					</div>

					<div class="flex gap-2 justify-end">
						<button type="button" class="btn btn-ghost" onclick={goBack}> Cancel </button>
						<button type="submit" class="btn btn-primary" disabled={!isValidInviteCode}>
							Join CCN
						</button>
					</div>
				</form>
			</div>
		{:else if mode === 'create'}
			<div class="p-4">
				<div class="flex items-center mb-4">
					<button class="btn btn-sm btn-ghost mr-2" onclick={goBack}>←</button>
					<h3 class="font-bold text-lg">Create New CCN</h3>
				</div>

				<form onsubmit={handleCreateCCN} class="space-y-4">
					<div class="form-control w-full">
						<label class="label" for="ccn-name">
							<span class="label-text">CCN Name</span>
						</label>
						<input
							id="ccn-name"
							type="text"
							placeholder="Enter CCN name..."
							class="input input-bordered w-full"
							bind:value={ccnName}
							required
						/>
					</div>

					<div class="form-control w-full">
						<label class="label" for="ccn-description">
							<span class="label-text">Description</span>
						</label>
						<textarea
							id="ccn-description"
							placeholder="Enter CCN description..."
							class="textarea textarea-bordered w-full"
							bind:value={ccnDescription}
							required
							rows="3"
						></textarea>
					</div>

					<div class="flex gap-2 justify-end">
						<button type="button" class="btn btn-ghost" onclick={goBack}>Cancel</button>
						<button
							type="submit"
							class="btn btn-primary"
							disabled={!ccnName.trim() || !ccnDescription.trim()}
						>
							Create CCN
						</button>
					</div>
				</form>
			</div>
		{/if}
	</div>
</div>
