<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 NotificationRuleForm from '$lib/components/admin/notifications/NotificationRuleForm.svelte';
	import { DeleteNotificationRuleStore, UpdateNotificationRuleStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { invalidateAll } from '$app/navigation';
	import { fromGlobalId } from '$lib/utils/relay';
	import type { AdminNotificationRules$result } from '$houdini';

	type NotificationRule = AdminNotificationRules$result['notificationRules'][number];

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

	let rules = $derived(data.rules?.data?.notificationRules ?? []);
	// Convert profile IDs from Relay global IDs to raw UUIDs to match notification rule target IDs
	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
		})) ?? []
	);

	// Rules filter state
	type StatusFilter = 'all' | 'active' | 'inactive';
	let statusFilter = $state<StatusFilter>('all');
	let searchQuery = $state('');

	// Filtered rules
	let filteredRules = $derived(
		rules.filter((rule) => {
			// Status filter
			if (statusFilter === 'active' && !rule.isActive) return false;
			if (statusFilter === 'inactive' && rule.isActive) return false;

			// Search filter
			if (searchQuery) {
				const query = searchQuery.toLowerCase();
				if (
					!rule.name.toLowerCase().includes(query) &&
					!rule.description?.toLowerCase().includes(query)
				) {
					return false;
				}
			}

			return true;
		})
	);

	// Edit state
	let editingRule = $state<NotificationRule | null>(null);

	// Delete state
	let showDeleteModal = $state(false);
	let isDeleting = $state(false);
	let ruleToDelete = $state<{ id: string; name: string } | null>(null);

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

	function getChannelLabel(channel: string): string {
		switch (channel) {
			case 'IN_APP':
				return 'In-App';
			case 'EMAIL':
				return 'Email';
			case 'SMS':
				return 'SMS';
			default:
				return channel;
		}
	}

	// Form handlers
	function showCreateForm() {
		editingRule = null;
		offCanvas.showRight({
			title: 'Create Notification Rule',
			content: createFormContent
		});
	}

	function showEditForm(rule: NotificationRule) {
		editingRule = rule;
		offCanvas.showRight({
			title: 'Edit Notification Rule',
			content: editFormContent
		});
	}

	function showCloneForm(rule: NotificationRule) {
		// Create a copy with modified name
		editingRule = {
			...rule,
			id: '', // Will be treated as create
			name: `${rule.name} (Copy)`
		} as NotificationRule;
		offCanvas.showRight({
			title: 'Clone Notification Rule',
			content: cloneFormContent
		});
	}

	async function handleSuccess() {
		await invalidateAll();
	}

	function promptDelete(id: string, name: string) {
		ruleToDelete = { id, name };
		showDeleteModal = true;
	}

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

		try {
			await deleteStore.mutate({ id: ruleToDelete.id });
			await invalidateAll();
		} catch (err) {
			console.error('Failed to delete rule:', err);
		} finally {
			isDeleting = false;
			showDeleteModal = false;
			ruleToDelete = null;
		}
	}

	async function toggleActive(rule: NotificationRule) {
		try {
			await updateStore.mutate({
				input: {
					id: rule.id,
					isActive: !rule.isActive
				}
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to toggle rule:', err);
		}
	}
</script>

{#snippet createFormContent()}
	<NotificationRuleForm {teamProfiles} {customerProfiles} onSuccess={handleSuccess} />
{/snippet}

{#snippet editFormContent()}
	{#if editingRule}
		<NotificationRuleForm
			rule={editingRule}
			{teamProfiles}
			{customerProfiles}
			onSuccess={handleSuccess}
		/>
	{/if}
{/snippet}

{#snippet cloneFormContent()}
	{#if editingRule}
		<NotificationRuleForm
			rule={{ ...editingRule, id: '' }}
			{teamProfiles}
			{customerProfiles}
			onSuccess={handleSuccess}
		/>
	{/if}
{/snippet}

<svelte:head>
	<title>Notification Rules - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<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"
						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>
						<h1
							class="text-2xl font-bold text-notification-600 md:text-3xl dark:text-notification-400"
						>
							Notification Rules
						</h1>
						<p class="mt-2 text-theme-secondary">
							Configure when and how notifications are sent to users.
						</p>
					</div>
				</div>
				<button
					type="button"
					onclick={showCreateForm}
					class="hidden items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600 sm:inline-flex"
				>
					<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="M12 4v16m8-8H4"
						/>
					</svg>
					<span>Add Rule</span>
				</button>
			</div>
		</div>

		<!-- Rules -->
		<!-- Status Filter -->
		<div class="mb-4 flex items-center gap-2">
			<button
				onclick={() => (statusFilter = 'all')}
				class="rounded-lg px-3 py-1.5 text-sm font-medium transition-colors {statusFilter === 'all'
					? 'bg-notification-500/10 text-notification-600 dark:text-notification-400'
					: 'text-theme-muted hover:bg-black/5 dark:hover:bg-white/10'}"
			>
				All ({rules.length})
			</button>
			<button
				onclick={() => (statusFilter = 'active')}
				class="rounded-lg px-3 py-1.5 text-sm font-medium transition-colors {statusFilter ===
				'active'
					? 'bg-success-500/10 text-success-600 dark:text-success-400'
					: 'text-theme-muted hover:bg-black/5 dark:hover:bg-white/10'}"
			>
				Active ({rules.filter((r) => r.isActive).length})
			</button>
			<button
				onclick={() => (statusFilter = 'inactive')}
				class="rounded-lg px-3 py-1.5 text-sm font-medium transition-colors {statusFilter ===
				'inactive'
					? 'bg-gray-500/10 text-gray-600 dark:text-gray-400'
					: 'text-theme-muted hover:bg-black/5 dark:hover:bg-white/10'}"
			>
				Inactive ({rules.filter((r) => !r.isActive).length})
			</button>
		</div>

		<!-- Search -->
		<div class="mb-6">
			<div class="relative">
				<svg
					class="absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2 text-theme-muted"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<input
					type="text"
					bind:value={searchQuery}
					placeholder="Search notification rules..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme-card py-2 pr-4 pl-10 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500"
				/>
			</div>
		</div>

		<!-- Rules List -->
		{#if filteredRules.length > 0}
			<div class="space-y-3">
				{#each filteredRules as rule (rule.id)}
					<div class="group relative card-notification">
						<a
							href="/admin/notifications/{rule.id}"
							class="absolute inset-0 z-0"
							aria-label="Edit {rule.name}"
						></a>
						<div class="flex items-start justify-between gap-4">
							<div class="min-w-0 flex-1">
								<div class="mb-2 flex flex-wrap items-center gap-2">
									<h3
										class="font-semibold text-theme transition-colors group-hover:text-primary-600 dark:group-hover:text-primary-400"
									>
										{rule.name}
									</h3>
									<span
										class={`inline-flex items-center rounded-full px-2 py-0.5 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>

								{#if rule.description}
									<p class="mb-3 text-sm text-theme-muted">{rule.description}</p>
								{/if}

								<!-- Badges Row -->
								<div class="flex flex-wrap items-center gap-2">
									<!-- Event Types Count -->
									<span
										class="inline-flex items-center gap-1 rounded-full bg-purple-500/10 px-2 py-0.5 text-xs font-medium text-purple-600 dark:text-purple-400"
									>
										<svg
											class="h-3 w-3"
											style="fill: none"
											viewBox="0 0 24 24"
											stroke="currentColor"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M13 10V3L4 14h7v7l9-11h-7z"
											/>
										</svg>
										{rule.eventTypes.length} event{rule.eventTypes.length !== 1 ? 's' : ''}
									</span>

									<!-- Channel Badges -->
									{#each rule.channels as channel (channel)}
										<span
											class="inline-flex items-center gap-1 rounded-full bg-blue-500/10 px-2 py-0.5 text-xs font-medium text-blue-600 dark:text-blue-400"
										>
											{#if channel === 'IN_APP'}
												<svg
													class="h-3 w-3"
													style="fill: none"
													viewBox="0 0 24 24"
													stroke="currentColor"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
													/>
												</svg>
											{:else if channel === 'EMAIL'}
												<svg
													class="h-3 w-3"
													style="fill: none"
													viewBox="0 0 24 24"
													stroke="currentColor"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
													/>
												</svg>
											{:else}
												<svg
													class="h-3 w-3"
													style="fill: none"
													viewBox="0 0 24 24"
													stroke="currentColor"
												>
													<path
														stroke-linecap="round"
														stroke-linejoin="round"
														stroke-width="2"
														d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"
													/>
												</svg>
											{/if}
											{getChannelLabel(channel)}
										</span>
									{/each}

									<!-- Target Roles -->
									{#if rule.targetRoles.length > 0}
										<span
											class="inline-flex items-center gap-1 rounded-full bg-orange-500/10 px-2 py-0.5 text-xs font-medium text-orange-600 dark:text-orange-400"
										>
											<svg
												class="h-3 w-3"
												style="fill: none"
												viewBox="0 0 24 24"
												stroke="currentColor"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"
												/>
											</svg>
											{rule.targetRoles
												.map((r) =>
													r === 'ADMIN' ? 'Admin' : r === 'TEAM_LEADER' ? 'Leader' : 'Member'
												)
												.join(', ')}
										</span>
									{/if}
								</div>
							</div>

							<!-- Actions -->
							<div class="relative z-10 flex flex-shrink-0 items-center gap-1">
								<!-- Toggle Active -->
								<button
									onclick={() => toggleActive(rule)}
									class="rounded-lg p-2 transition-colors hover:bg-black/10 dark:hover:bg-white/10"
									title={rule.isActive ? 'Deactivate' : 'Activate'}
								>
									{#if rule.isActive}
										<svg
											class="h-4 w-4 text-success-500"
											style="fill: none"
											viewBox="0 0 24 24"
											stroke="currentColor"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
											/>
										</svg>
									{:else}
										<svg
											class="h-4 w-4 text-theme-muted"
											style="fill: none"
											viewBox="0 0 24 24"
											stroke="currentColor"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
											/>
										</svg>
									{/if}
								</button>

								<!-- Clone -->
								<button
									onclick={() => showCloneForm(rule)}
									class="rounded-lg p-2 transition-colors hover:bg-black/10 dark:hover:bg-white/10"
									title="Duplicate"
								>
									<svg
										class="h-4 w-4 text-theme-muted"
										style="fill: none"
										viewBox="0 0 24 24"
										stroke="currentColor"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
										/>
									</svg>
								</button>

								<!-- Edit -->
								<button
									onclick={() => showEditForm(rule)}
									class="rounded-lg bg-notification-500/10 px-3 py-1.5 text-sm font-medium text-notification-600 transition-colors hover:bg-notification-500/20 dark:text-notification-400"
								>
									Edit
								</button>

								<!-- Delete -->
								<button
									onclick={() => promptDelete(rule.id, rule.name)}
									class="rounded-lg bg-error-500/10 p-1.5 text-error-600 transition-colors hover:bg-error-500/20 dark:text-error-400"
									title="Delete"
								>
									<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>
								</button>
							</div>
						</div>
					</div>
				{/each}
			</div>
		{:else if searchQuery}
			<div class="empty-state">
				<svg class="empty-state-icon" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<h2 class="empty-state-title">No rules found</h2>
				<p class="empty-state-text">
					No notification rules match "{searchQuery}". Try a different search term.
				</p>
			</div>
		{:else}
			<div class="empty-state">
				<svg class="empty-state-icon" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
					/>
				</svg>
				<h2 class="empty-state-title">No notification rules yet</h2>
				<p class="empty-state-text">
					Get started by creating your first notification rule to automate alerts.
				</p>
				<button
					type="button"
					onclick={showCreateForm}
					class="mt-4 inline-flex items-center gap-2 rounded-lg bg-primary-500 px-4 py-2 text-white transition-colors hover:bg-primary-600"
				>
					<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="M12 4v16m8-8H4"
						/>
					</svg>
					<span>Create Rule</span>
				</button>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Mobile FAB -->
<button
	type="button"
	onclick={showCreateForm}
	class="fixed right-4 bottom-20 z-30 flex h-14 w-14 items-center justify-center rounded-full bg-primary-500 text-white shadow-lg transition-colors hover:bg-primary-600 sm:hidden"
	aria-label="Add notification rule"
>
	<svg class="h-6 w-6" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
		<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
	</svg>
</button>

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