<script lang="ts">
	import type { PageData } from './$types';
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import EventTypeSelector from '$lib/components/admin/notifications/EventTypeSelector.svelte';
	import ChannelSelector from '$lib/components/admin/notifications/ChannelSelector.svelte';
	import TargetSelector from '$lib/components/admin/notifications/TargetSelector.svelte';
	import TemplateEditor from '$lib/components/admin/notifications/TemplateEditor.svelte';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';
	import {
		UpdateNotificationRuleStore,
		DeleteNotificationRuleStore,
		type EventTypeChoices$options,
		type NotificationChannelChoices$options,
		type RoleChoices$options
	} from '$houdini';
	import { goto, invalidateAll } from '$app/navigation';
	import { fromGlobalId } from '$lib/utils/relay';
	import { formatDate } from '$lib/utils/date';

	let { data }: { data: PageData } = $props();

	let rule = $derived(data.rule?.data?.notificationRule);

	// Convert profile IDs from Relay global IDs to raw UUIDs
	let teamProfiles = $derived(
		data.profiles?.data?.teamProfiles?.map((p) => ({
			id: fromGlobalId(p.id),
			fullName: p.fullName,
			email: p.email,
			role: p.role
		})) ?? []
	);
	let customerProfiles = $derived(
		data.profiles?.data?.customerProfiles?.map((p) => ({
			id: fromGlobalId(p.id),
			fullName: p.fullName,
			email: p.email
		})) ?? []
	);

	// Form state
	let submitting = $state(false);
	let error = $state('');
	let successMessage = $state('');
	let formInitialized = $state(false);

	let name = $state('');
	let description = $state('');
	let eventTypes = $state<string[]>([]);
	let channels = $state<string[]>(['IN_APP']);
	let targetRoles = $state<string[]>([]);
	let targetTeamProfileIds = $state<string[]>([]);
	let targetCustomerProfileIds = $state<string[]>([]);
	let templateSubject = $state('');
	let templateBody = $state('');
	let conditions = $state<string>('');
	let isActive = $state(true);

	let conditionsError = $state('');

	// Initialize form state from rule data (only once on initial load)
	$effect(() => {
		if (rule && !formInitialized) {
			name = rule.name ?? '';
			description = rule.description ?? '';
			eventTypes = [...(rule.eventTypes ?? [])];
			channels = [...(rule.channels ?? ['IN_APP'])];
			targetRoles = [...(rule.targetRoles ?? [])];
			targetTeamProfileIds = [...(rule.targetTeamProfileIds ?? [])];
			targetCustomerProfileIds = [...(rule.targetCustomerProfileIds ?? [])];
			templateSubject = rule.templateSubject ?? '';
			templateBody = rule.templateBody ?? '';
			conditions = rule.conditions ? JSON.stringify(rule.conditions, null, 2) : '';
			isActive = rule.isActive ?? true;
			formInitialized = true;
		}
	});

	const updateStore = new UpdateNotificationRuleStore();
	const deleteStore = new DeleteNotificationRuleStore();

	const conditionsExample = '{"status": "COMPLETED"}';

	const roleOptions = [
		{ value: 'ADMIN', label: 'Admin' },
		{ value: 'TEAM_LEADER', label: 'Team Leader' },
		{ value: 'TEAM_MEMBER', label: 'Team Member' }
	];

	// Delete state
	let showDeleteModal = $state(false);
	let isDeleting = $state(false);

	function toggleRole(role: string) {
		if (targetRoles.includes(role)) {
			targetRoles = targetRoles.filter((r) => r !== role);
		} else {
			targetRoles = [...targetRoles, role];
		}
	}

	function parseConditions(): Record<string, unknown> | null {
		if (!conditions.trim()) return null;
		try {
			const parsed = JSON.parse(conditions);
			conditionsError = '';
			return parsed;
		} catch {
			conditionsError = 'Invalid JSON';
			return null;
		}
	}

	async function handleSubmit(e: SubmitEvent) {
		e.preventDefault();
		if (!rule) return;

		submitting = true;
		error = '';
		successMessage = '';

		try {
			// Validation
			if (!name.trim()) {
				error = 'Please provide a name for the rule';
				return;
			}

			if (eventTypes.length === 0) {
				error = 'Please select at least one event type';
				return;
			}

			if (channels.length === 0) {
				error = 'Please select at least one notification channel';
				return;
			}

			// Parse conditions if provided
			let parsedConditions: Record<string, unknown> | null = null;
			if (conditions.trim()) {
				parsedConditions = parseConditions();
				if (conditionsError) {
					error = 'Invalid JSON in conditions field';
					return;
				}
			}

			const res = await updateStore.mutate({
				input: {
					id: rule.id,
					name: name.trim(),
					description: description.trim() || null,
					eventTypes: eventTypes as EventTypeChoices$options[],
					channels: channels as NotificationChannelChoices$options[],
					targetRoles: targetRoles.length > 0 ? (targetRoles as RoleChoices$options[]) : null,
					targetTeamProfileIds: targetTeamProfileIds.length > 0 ? targetTeamProfileIds : null,
					targetCustomerProfileIds:
						targetCustomerProfileIds.length > 0 ? targetCustomerProfileIds : null,
					templateSubject: templateSubject.trim() || null,
					templateBody: templateBody.trim() || null,
					conditions: parsedConditions,
					isActive
				}
			});

			if (res.errors?.length) {
				error = res.errors.map((e: { message: string }) => e.message).join(', ');
				return;
			}

			successMessage = 'Changes saved successfully';
			await invalidateAll();

			// Clear success message after 3 seconds
			setTimeout(() => {
				successMessage = '';
			}, 3000);
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to save notification rule';
		} finally {
			submitting = false;
		}
	}

	async function handleDelete() {
		if (!rule) return;
		isDeleting = true;

		try {
			await deleteStore.mutate({ id: rule.id });
			await goto('/admin/notifications');
		} catch (err) {
			console.error('Failed to delete rule:', err);
			error = err instanceof Error ? err.message : 'Failed to delete rule';
		} finally {
			isDeleting = false;
			showDeleteModal = false;
		}
	}
</script>

<svelte:head>
	<title>{rule?.name ?? 'Notification Rule'} - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		{#if rule}
			<!-- Header -->
			<div class="mb-8">
				<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
					<div class="flex items-start gap-4">
						<a
							href="/admin/notifications"
							class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
							aria-label="Go back"
						>
							<svg class="h-5 w-5" style="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>
							<div class="flex items-center gap-3">
								<h1
									class="text-2xl font-bold text-notification-600 md:text-3xl dark:text-notification-400"
								>
									{rule.name}
								</h1>
								<span
									class={`inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium ${
										rule.isActive
											? 'bg-success-500/10 text-success-600 dark:text-success-400'
											: 'bg-gray-500/10 text-gray-600 dark:text-gray-400'
									}`}
								>
									{rule.isActive ? 'Active' : 'Inactive'}
								</span>
							</div>
							<p class="mt-1 text-sm text-theme-muted">
								Created {formatDate(rule.createdAt) || '—'} · Last updated {formatDate(
									rule.updatedAt
								) || '—'}
							</p>
						</div>
					</div>
					<button
						type="button"
						onclick={() => (showDeleteModal = true)}
						class="inline-flex items-center gap-2 rounded-lg border border-error-500 px-4 py-2 text-sm font-medium text-error-600 transition-colors hover:bg-error-500/10 dark:text-error-400"
					>
						<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
							/>
						</svg>
						Delete Rule
					</button>
				</div>
			</div>

			<!-- Messages -->
			{#if error}
				<div class="mb-6 alert-error">{error}</div>
			{/if}

			{#if successMessage}
				<div
					class="mb-6 rounded-lg border border-success-400 bg-success-50 p-4 text-sm text-success-700 dark:border-success-600 dark:bg-success-900/20 dark:text-success-400"
				>
					{successMessage}
				</div>
			{/if}

			<!-- Form -->
			<form class="space-y-8" onsubmit={handleSubmit}>
				<!-- Basic Info Section -->
				<section class="card-notification">
					<h2 class="mb-4 text-lg font-semibold text-theme">Basic Information</h2>
					<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
						<div class="sm:col-span-2">
							<label for="name" class="mb-1.5 block text-sm font-medium text-theme">
								Name <span class="text-error-500">*</span>
							</label>
							<input
								id="name"
								type="text"
								bind:value={name}
								disabled={submitting}
								placeholder="e.g., Service Completion Alert"
								class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
							/>
						</div>

						<div class="sm:col-span-2">
							<label for="description" class="mb-1.5 block text-sm font-medium text-theme">
								Description
							</label>
							<textarea
								id="description"
								bind:value={description}
								disabled={submitting}
								rows={2}
								placeholder="Describe when this rule triggers and what it does"
								class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
							></textarea>
						</div>

						<div class="sm:col-span-2">
							<label class="flex cursor-pointer items-center gap-3">
								<input
									type="checkbox"
									bind:checked={isActive}
									disabled={submitting}
									class="border-theme-muted h-5 w-5 rounded text-primary-500 focus:ring-primary-500"
								/>
								<span class="text-sm font-medium text-theme">Active</span>
								<span class="text-xs text-theme-muted">
									{isActive ? 'This rule will trigger notifications' : 'This rule is disabled'}
								</span>
							</label>
						</div>
					</div>
				</section>

				<!-- Event Types Section -->
				<section class="card-notification">
					<h2 class="mb-4 text-lg font-semibold text-theme">Trigger Events</h2>
					<p class="mb-4 text-sm text-theme-muted">
						Select which events will trigger this notification rule.
					</p>
					<EventTypeSelector bind:selected={eventTypes} />
				</section>

				<!-- Channels Section -->
				<section class="card-notification">
					<h2 class="mb-4 text-lg font-semibold text-theme">Delivery Channels</h2>
					<p class="mb-4 text-sm text-theme-muted">
						Choose how notifications will be delivered to recipients.
					</p>
					<ChannelSelector bind:selected={channels} />
				</section>

				<!-- Recipients Section -->
				<section class="card-notification">
					<h2 class="mb-4 text-lg font-semibold text-theme">Recipients</h2>
					<p class="mb-4 text-sm text-theme-muted">
						Define who will receive notifications when this rule triggers.
					</p>

					<div class="space-y-6">
						<!-- Target by Role -->
						<div>
							<span class="mb-2 block text-sm font-medium text-theme">Target by Role</span>
							<p class="mb-3 text-xs text-theme-muted">
								Leave empty to notify all roles. Select specific roles to limit recipients.
							</p>
							<div class="flex flex-wrap gap-2">
								{#each roleOptions as role (role.value)}
									<button
										type="button"
										onclick={() => toggleRole(role.value)}
										disabled={submitting}
										class="rounded-lg border px-3 py-1.5 text-sm transition-colors {targetRoles.includes(
											role.value
										)
											? 'border-primary-500 bg-primary-500/10 text-primary-600 dark:text-primary-400'
											: 'border-theme bg-theme hover:bg-black/5 dark:hover:bg-white/10'}"
									>
										{role.label}
									</button>
								{/each}
							</div>
							{#if targetRoles.length === 0}
								<p class="mt-2 text-xs text-success-600 dark:text-success-400">
									All team members will receive notifications
								</p>
							{/if}
						</div>

						<!-- Specific Team Members -->
						<TargetSelector
							label="Specific Team Members"
							profiles={teamProfiles}
							bind:selectedIds={targetTeamProfileIds}
							placeholder="Search team members..."
						/>

						<!-- Specific Customers -->
						<TargetSelector
							label="Specific Customers"
							profiles={customerProfiles}
							bind:selectedIds={targetCustomerProfileIds}
							placeholder="Search customers..."
						/>
					</div>
				</section>

				<!-- Template Section -->
				<section class="card-notification">
					<h2 class="mb-4 text-lg font-semibold text-theme">Message Template</h2>
					<p class="mb-4 text-sm text-theme-muted">
						Customize the notification message. Use variables to include dynamic content.
					</p>
					<TemplateEditor bind:subject={templateSubject} bind:body={templateBody} />
				</section>

				<!-- Advanced Options Section -->
				<section class="card-notification">
					<h2 class="mb-4 text-lg font-semibold text-theme">Advanced Options</h2>
					<div>
						<label for="conditions" class="mb-1.5 block text-sm font-medium text-theme">
							Conditions (JSON)
						</label>
						<p class="mb-2 text-xs text-theme-muted">
							Add JSON conditions to filter events. Example: {conditionsExample}
						</p>
						<textarea
							id="conditions"
							bind:value={conditions}
							oninput={() => parseConditions()}
							disabled={submitting}
							rows={4}
							placeholder={conditionsExample}
							class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 font-mono text-sm text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
						></textarea>
						{#if conditionsError}
							<p class="mt-1 text-xs text-error-500">{conditionsError}</p>
						{/if}
					</div>
				</section>

				<!-- Actions -->
				<div class="flex items-center gap-4">
					<button
						type="submit"
						disabled={submitting}
						class="rounded-lg bg-primary-500 px-6 py-2.5 font-medium text-white transition-colors hover:bg-primary-600 disabled:cursor-not-allowed disabled:opacity-50"
					>
						{#if submitting}
							<span class="flex items-center gap-2">
								<IconSpinner class="h-4 w-4" />
								<span>Saving...</span>
							</span>
						{:else}
							Save Changes
						{/if}
					</button>
					<a
						href="/admin/notifications"
						class="rounded-lg border border-theme interactive bg-theme px-6 py-2.5 font-medium text-theme"
					>
						Cancel
					</a>
				</div>
			</form>
		{:else}
			<div class="py-12 text-center">
				<p class="text-theme-muted">Rule not found</p>
			</div>
		{/if}
	</ContentContainer>
</div>

<DeleteConfirmModal
	bind:open={showDeleteModal}
	title="Delete Notification Rule"
	message="Are you sure you want to delete '{rule?.name}'? This action cannot be undone."
	onconfirm={handleDelete}
	oncancel={() => {}}
	loading={isDeleting}
/>
