<script lang="ts">
	import { goto } from '$app/navigation';
	import { ContentContainer } from '$lib/components/layout';
	import { client } from '$lib/graphql/client';
	import {
		CREATE_CALENDAR_EVENT,
		type CreateCalendarEventInput,
		type CreateCalendarEventResult
	} from '$lib/graphql/mutations/calendar';
	import { EVENT_COLORS } from '$lib/graphql/queries/calendar';

	let isSaving = $state(false);
	let errorMessage = $state<string | null>(null);

	// Form state
	let summary = $state('');
	let description = $state('');
	let location = $state('');
	let colorId = $state('');
	let allDay = $state(true);
	let startDate = $state(new Date().toISOString().split('T')[0]);
	let endDate = $state(new Date().toISOString().split('T')[0]);
	let startDateTime = $state('');
	let endDateTime = $state('');

	async function handleSubmit(e: SubmitEvent) {
		e.preventDefault();
		isSaving = true;
		errorMessage = null;

		try {
			const input: CreateCalendarEventInput = {
				summary,
				description: description || undefined,
				location: location || undefined,
				colorId: colorId || undefined,
				start: allDay ? { date: startDate } : { dateTime: new Date(startDateTime).toISOString() },
				end: allDay ? { date: endDate } : { dateTime: new Date(endDateTime).toISOString() }
			};

			const result = await client.mutate<CreateCalendarEventResult>({
				mutation: CREATE_CALENDAR_EVENT,
				variables: { input }
			});

			if (result.data?.createCalendarEvent?.id) {
				goto(`/admin/calendar/${result.data.createCalendarEvent.id}`);
			} else {
				throw new Error('No event ID returned');
			}
		} catch (err) {
			console.error('Failed to create event:', err);
			errorMessage = err instanceof Error ? err.message : 'Failed to create event';
		} finally {
			isSaving = false;
		}
	}
</script>

<svelte:head>
	<title>Create Event - Calendar - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<div class="mb-6 flex items-start gap-4">
			<a
				href="/admin/calendar"
				class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
				aria-label="Back to calendar"
			>
				<svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M15 19l-7-7 7-7"
					/>
				</svg>
			</a>
			<div>
				<h1 class="text-2xl font-bold text-accent7-600 md:text-3xl dark:text-accent7-400">
					Create Event
				</h1>
				<p class="mt-1 text-sm text-theme-secondary">Add a new event to the calendar</p>
			</div>
		</div>

		<!-- Form -->
		<div class="rounded-xl border border-theme bg-theme p-6">
			{#if errorMessage}
				<div
					class="mb-4 rounded-lg border border-error-500/30 bg-error-50/50 p-3 dark:bg-error-950/30"
				>
					<p class="text-sm text-error-700 dark:text-error-400">{errorMessage}</p>
				</div>
			{/if}

			<form onsubmit={handleSubmit} class="space-y-4">
				<label class="block">
					<span class="text-sm font-medium text-theme"
						>Summary <span class="text-error-500">*</span></span
					>
					<input
						type="text"
						bind:value={summary}
						class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
						required
						disabled={isSaving}
					/>
				</label>

				<label class="block">
					<span class="text-sm font-medium text-theme">Description</span>
					<textarea
						bind:value={description}
						rows="3"
						class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
						disabled={isSaving}
					></textarea>
				</label>

				<label class="block">
					<span class="text-sm font-medium text-theme">Location</span>
					<input
						type="text"
						bind:value={location}
						class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
						disabled={isSaving}
					/>
				</label>

				<label class="block">
					<span class="text-sm font-medium text-theme">Color</span>
					<select
						bind:value={colorId}
						class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
						disabled={isSaving}
					>
						<option value="">Default</option>
						{#each EVENT_COLORS as color (color.id)}
							<option value={color.id}>{color.name}</option>
						{/each}
					</select>
				</label>

				<label class="flex items-center gap-2">
					<input
						type="checkbox"
						bind:checked={allDay}
						class="h-4 w-4 rounded border-theme text-accent7-500 focus:ring-accent7-500"
						disabled={isSaving}
					/>
					<span class="text-sm font-medium text-theme">All day event</span>
				</label>

				{#if allDay}
					<div class="grid gap-4 sm:grid-cols-2">
						<label class="block">
							<span class="text-sm font-medium text-theme"
								>Start Date <span class="text-error-500">*</span></span
							>
							<input
								type="date"
								bind:value={startDate}
								class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
								required
								disabled={isSaving}
							/>
						</label>
						<label class="block">
							<span class="text-sm font-medium text-theme"
								>End Date <span class="text-error-500">*</span></span
							>
							<input
								type="date"
								bind:value={endDate}
								class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
								required
								disabled={isSaving}
							/>
						</label>
					</div>
				{:else}
					<div class="grid gap-4 sm:grid-cols-2">
						<label class="block">
							<span class="text-sm font-medium text-theme"
								>Start <span class="text-error-500">*</span></span
							>
							<input
								type="datetime-local"
								bind:value={startDateTime}
								class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
								required
								disabled={isSaving}
							/>
						</label>
						<label class="block">
							<span class="text-sm font-medium text-theme"
								>End <span class="text-error-500">*</span></span
							>
							<input
								type="datetime-local"
								bind:value={endDateTime}
								class="mt-1 block w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500 focus:outline-none"
								required
								disabled={isSaving}
							/>
						</label>
					</div>
				{/if}

				<div class="flex justify-end gap-3 pt-4">
					<a href="/admin/calendar" class="btn-outline"> Cancel </a>
					<button type="submit" class="btn-accent7" disabled={isSaving}>
						{isSaving ? 'Creating...' : 'Create Event'}
					</button>
				</div>
			</form>
		</div>
	</ContentContainer>
</div>
