<script lang="ts">
	import { client } from '$lib/graphql/client';
	import type { PageData } from './$types';
	import { ContentContainer } from '$lib/components/layout';
	import { AdminDashboardHeader } from '$lib/components/admin';
	import type { NotificationRule } from '$lib/graphql/queries/notifications';
	import type { TeamProfile } from '$lib/graphql/queries/team';
	import {
		CREATE_NOTIFICATION_RULE,
		UPDATE_NOTIFICATION_RULE,
		DELETE_NOTIFICATION_RULE,
		TOGGLE_NOTIFICATION_RULE,
		type CreateNotificationRuleInput,
		type UpdateNotificationRuleInput,
		type CreateNotificationRuleResult,
		type UpdateNotificationRuleResult,
		type DeleteNotificationRuleResult,
		type ToggleNotificationRuleResult
	} from '$lib/graphql/mutations/notifications';

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

	let rulesOverride = $state<NotificationRule[] | null>(null);
	let rules = $derived(rulesOverride ?? (data.rules as NotificationRule[]));
	let teamProfiles = $derived(data.teamProfiles as TeamProfile[]);

	// Modal state
	let showModal = $state(false);
	let editingRule = $state<NotificationRule | null>(null);
	let isSubmitting = $state(false);
	let error = $state('');

	// Form state
	let formName = $state('');
	let formDescription = $state('');
	let formEventTypes = $state<string[]>([]);
	let formChannels = $state<string[]>(['IN_APP']);
	let formTargetRoles = $state<string[]>([]);
	let formSubjectTemplate = $state('');
	let formBodyTemplate = $state('');
	let formTargetTeamProfileIds = $state<string[]>([]);

	// Available options
	const eventTypeOptions = [
		'ServiceCreated',
		'ServiceUpdated',
		'ServiceCompleted',
		'ServiceCancelled',
		'ProjectCreated',
		'ProjectUpdated',
		'ProjectCompleted',
		'ProjectCancelled',
		'InvoiceGenerated',
		'InvoiceSent',
		'InvoicePaid',
		'InvoiceOverdue',
		'SessionStarted',
		'SessionCompleted',
		'ReportGenerated'
	];

	const channelOptions = [
		{ value: 'IN_APP', label: 'In-App' },
		{ value: 'EMAIL', label: 'Email' },
		{ value: 'SMS', label: 'SMS' }
	];

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

	function openCreateModal() {
		editingRule = null;
		formName = '';
		formDescription = '';
		formEventTypes = [];
		formChannels = ['IN_APP'];
		formTargetRoles = [];
		formSubjectTemplate = '';
		formBodyTemplate = '';
		formTargetTeamProfileIds = [];
		error = '';
		showModal = true;
	}

	function openEditModal(rule: NotificationRule) {
		editingRule = rule;
		formName = rule.name;
		formDescription = rule.description ?? '';
		formEventTypes = Array.isArray(rule.eventTypes) ? rule.eventTypes : [];
		formChannels = Array.isArray(rule.channels) ? rule.channels : ['IN_APP'];
		formTargetRoles = Array.isArray(rule.targetRoles) ? rule.targetRoles : [];
		formSubjectTemplate = rule.subjectTemplate ?? '';
		formBodyTemplate = rule.bodyTemplate ?? '';
		formTargetTeamProfileIds = rule.targetTeamProfiles?.map((p) => p.id) ?? [];
		error = '';
		showModal = true;
	}

	async function handleSubmit() {
		if (!formName.trim()) {
			error = 'Name is required';
			return;
		}

		if (formEventTypes.length === 0) {
			error = 'Select at least one event type';
			return;
		}

		if (formChannels.length === 0) {
			error = 'Select at least one channel';
			return;
		}

		isSubmitting = true;
		error = '';

		try {
			if (editingRule) {
				// Update existing rule
				const input: UpdateNotificationRuleInput = {
					name: formName.trim(),
					description: formDescription.trim() || undefined,
					eventTypes: formEventTypes,
					channels: formChannels,
					targetRoles: formTargetRoles.length > 0 ? formTargetRoles : undefined,
					subjectTemplate: formSubjectTemplate.trim() || undefined,
					bodyTemplate: formBodyTemplate.trim() || undefined,
					targetTeamProfileIds:
						formTargetTeamProfileIds.length > 0 ? formTargetTeamProfileIds : undefined
				};

				const result = await client.mutate<UpdateNotificationRuleResult>({
					mutation: UPDATE_NOTIFICATION_RULE,
					variables: { id: editingRule.id, input }
				});

				if (result.data?.updateNotificationRule) {
					rulesOverride = rules.map((r) =>
						r.id === editingRule!.id ? { ...r, ...result.data!.updateNotificationRule } : r
					);
				}
			} else {
				// Create new rule
				const input: CreateNotificationRuleInput = {
					name: formName.trim(),
					description: formDescription.trim() || undefined,
					eventTypes: formEventTypes,
					channels: formChannels,
					targetRoles: formTargetRoles.length > 0 ? formTargetRoles : undefined,
					subjectTemplate: formSubjectTemplate.trim() || undefined,
					bodyTemplate: formBodyTemplate.trim() || undefined,
					targetTeamProfileIds:
						formTargetTeamProfileIds.length > 0 ? formTargetTeamProfileIds : undefined
				};

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

				if (result.data?.createNotificationRule) {
					rulesOverride = [...rules, result.data.createNotificationRule];
				}
			}

			showModal = false;
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to save rule';
		} finally {
			isSubmitting = false;
		}
	}

	async function handleToggle(rule: NotificationRule) {
		try {
			const result = await client.mutate<ToggleNotificationRuleResult>({
				mutation: TOGGLE_NOTIFICATION_RULE,
				variables: { id: rule.id, isActive: !rule.isActive }
			});

			if (result.data?.toggleNotificationRule) {
				rulesOverride = rules.map((r) =>
					r.id === rule.id ? { ...r, isActive: result.data!.toggleNotificationRule.isActive } : r
				);
			}
		} catch (err) {
			console.error('Failed to toggle rule:', err);
		}
	}

	async function handleDelete(rule: NotificationRule) {
		if (!confirm(`Are you sure you want to delete "${rule.name}"?`)) return;

		try {
			await client.mutate<DeleteNotificationRuleResult>({
				mutation: DELETE_NOTIFICATION_RULE,
				variables: { id: rule.id }
			});

			rulesOverride = rules.filter((r) => r.id !== rule.id);
		} catch (err) {
			console.error('Failed to delete rule:', err);
		}
	}

	function toggleEventType(eventType: string) {
		if (formEventTypes.includes(eventType)) {
			formEventTypes = formEventTypes.filter((e) => e !== eventType);
		} else {
			formEventTypes = [...formEventTypes, eventType];
		}
	}

	function toggleChannel(channel: string) {
		if (formChannels.includes(channel)) {
			formChannels = formChannels.filter((c) => c !== channel);
		} else {
			formChannels = [...formChannels, channel];
		}
	}

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

	function toggleTeamProfile(profileId: string) {
		if (formTargetTeamProfileIds.includes(profileId)) {
			formTargetTeamProfileIds = formTargetTeamProfileIds.filter((id) => id !== profileId);
		} else {
			formTargetTeamProfileIds = [...formTargetTeamProfileIds, profileId];
		}
	}
</script>

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

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<AdminDashboardHeader
			title="Notification Rules"
			subtitle="{rules.length} rule{rules.length !== 1 ? 's' : ''}"
		>
			{#snippet actions()}
				<button type="button" class="btn-primary flex items-center gap-2" onclick={openCreateModal}>
					<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="M12 4v16m8-8H4"
						/>
					</svg>
					Create Rule
				</button>
			{/snippet}
		</AdminDashboardHeader>

		<!-- Rules List -->
		{#if rules.length > 0}
			<div class="space-y-4">
				{#each rules as rule (rule.id)}
					<div class="rounded-lg border border-theme bg-theme-card p-4">
						<div class="flex items-start justify-between gap-4">
							<div class="min-w-0 flex-1">
								<div class="flex items-center gap-3">
									<h3 class="font-semibold text-theme">{rule.name}</h3>
									<span
										class="rounded-full px-2 py-0.5 text-xs font-medium {rule.isActive
											? 'bg-success-100 text-success-800 dark:bg-success-900/30 dark:text-success-400'
											: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400'}"
									>
										{rule.isActive ? 'Active' : 'Inactive'}
									</span>
								</div>
								{#if rule.description}
									<p class="mt-1 text-sm text-theme-secondary">{rule.description}</p>
								{/if}

								<!-- Tags -->
								<div class="mt-3 flex flex-wrap gap-2">
									<!-- Event types -->
									{#each (Array.isArray(rule.eventTypes) ? rule.eventTypes : []).slice(0, 3) as eventType}
										<span
											class="rounded bg-purple-100 px-2 py-0.5 text-xs text-purple-800 dark:bg-purple-900/30 dark:text-purple-400"
										>
											{eventType}
										</span>
									{/each}
									{#if Array.isArray(rule.eventTypes) && rule.eventTypes.length > 3}
										<span class="text-xs text-theme-muted">
											+{rule.eventTypes.length - 3} more
										</span>
									{/if}

									<!-- Channels -->
									{#each Array.isArray(rule.channels) ? rule.channels : [] as channel}
										<span
											class="rounded bg-accent-100 px-2 py-0.5 text-xs text-accent-800 dark:bg-accent-900/30 dark:text-accent-400"
										>
											{channel}
										</span>
									{/each}
								</div>
							</div>

							<!-- Actions -->
							<div class="flex shrink-0 items-center gap-2">
								<button
									type="button"
									class="hover:bg-theme-hover rounded p-2 text-theme-muted hover:text-theme"
									onclick={() => handleToggle(rule)}
									aria-label={rule.isActive ? 'Disable rule' : 'Enable rule'}
								>
									{#if rule.isActive}
										<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="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"
											/>
										</svg>
									{:else}
										<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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
											/>
										</svg>
									{/if}
								</button>
								<button
									type="button"
									class="hover:bg-theme-hover rounded p-2 text-theme-muted hover:text-theme"
									onclick={() => openEditModal(rule)}
									aria-label="Edit rule"
								>
									<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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
										/>
									</svg>
								</button>
								<button
									type="button"
									class="rounded p-2 text-theme-muted hover:bg-red-100 hover:text-red-600 dark:hover:bg-red-900/30 dark:hover:text-red-400"
									onclick={() => handleDelete(rule)}
									aria-label="Delete rule"
								>
									<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="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}
			<!-- Empty state -->
			<div class="rounded-lg border border-dashed border-theme py-12 text-center">
				<svg
					class="mx-auto h-12 w-12 text-theme-muted"
					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>
				<h3 class="mt-4 text-lg font-medium text-theme">No notification rules</h3>
				<p class="mt-2 text-theme-secondary">
					Create a rule to start sending notifications for events.
				</p>
				<button type="button" class="mt-4 btn-primary" onclick={openCreateModal}>
					Create Rule
				</button>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Create/Edit Modal -->
{#if showModal}
	<div class="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto p-4 pt-16">
		<button
			type="button"
			class="fixed inset-0 bg-black/50"
			onclick={() => (showModal = false)}
			aria-label="Close modal"
		></button>
		<div
			class="relative w-full max-w-2xl rounded-xl border border-theme bg-theme-card p-6 shadow-xl"
		>
			<h2 class="mb-4 text-lg font-semibold text-theme">
				{editingRule ? 'Edit Rule' : 'Create Rule'}
			</h2>

			{#if error}
				<div
					class="mb-4 rounded-lg bg-red-100 p-3 text-sm text-red-700 dark:bg-red-900/30 dark:text-red-400"
				>
					{error}
				</div>
			{/if}

			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleSubmit();
				}}
			>
				<!-- Name -->
				<label class="mb-4 block">
					<span class="mb-1 block text-sm font-medium text-theme">Name *</span>
					<input
						type="text"
						bind:value={formName}
						placeholder="e.g., Service Completion Alert"
						class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
						required
					/>
				</label>

				<!-- Description -->
				<label class="mb-4 block">
					<span class="mb-1 block text-sm font-medium text-theme">Description</span>
					<textarea
						bind:value={formDescription}
						placeholder="Describe what this rule does..."
						rows="2"
						class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
					></textarea>
				</label>

				<!-- Event Types -->
				<div class="mb-4">
					<span class="mb-2 block text-sm font-medium text-theme">Event Types *</span>
					<div
						class="flex max-h-40 flex-wrap gap-2 overflow-y-auto rounded-lg border border-theme p-3"
					>
						{#each eventTypeOptions as eventType}
							<button
								type="button"
								class="rounded-full px-3 py-1 text-sm transition-colors {formEventTypes.includes(
									eventType
								)
									? 'bg-purple-500 text-white'
									: 'bg-gray-100 text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600'}"
								onclick={() => toggleEventType(eventType)}
							>
								{eventType}
							</button>
						{/each}
					</div>
				</div>

				<!-- Channels -->
				<div class="mb-4">
					<span class="mb-2 block text-sm font-medium text-theme">Channels *</span>
					<div class="flex gap-4">
						{#each channelOptions as channel}
							<label class="flex items-center gap-2">
								<input
									type="checkbox"
									checked={formChannels.includes(channel.value)}
									onchange={() => toggleChannel(channel.value)}
									class="rounded border-theme text-accent-500"
								/>
								<span class="text-theme">{channel.label}</span>
							</label>
						{/each}
					</div>
				</div>

				<!-- Target Roles -->
				<div class="mb-4">
					<span class="mb-2 block text-sm font-medium text-theme">Target Roles (optional)</span>
					<div class="flex gap-4">
						{#each roleOptions as role}
							<label class="flex items-center gap-2">
								<input
									type="checkbox"
									checked={formTargetRoles.includes(role.value)}
									onchange={() => toggleRole(role.value)}
									class="rounded border-theme text-accent-500"
								/>
								<span class="text-theme">{role.label}</span>
							</label>
						{/each}
					</div>
				</div>

				<!-- Subject Template -->
				<label class="mb-4 block">
					<span class="mb-1 block text-sm font-medium text-theme">Subject Template</span>
					<input
						type="text"
						bind:value={formSubjectTemplate}
						placeholder={'e.g., Service completed for {{customer_name}}'}
						class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
					/>
					<span class="mt-1 block text-xs text-theme-muted">
						Use {'{{variable}}'} for dynamic content
					</span>
				</label>

				<!-- Body Template -->
				<label class="mb-4 block">
					<span class="mb-1 block text-sm font-medium text-theme">Body Template</span>
					<textarea
						bind:value={formBodyTemplate}
						placeholder={'The service at {{address}} has been completed.'}
						rows="3"
						class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme"
					></textarea>
				</label>

				<!-- Target Team Profiles -->
				{#if teamProfiles.length > 0}
					<div class="mb-6">
						<span class="mb-2 block text-sm font-medium text-theme">
							Specific Team Members (optional)
						</span>
						<div class="max-h-40 overflow-y-auto rounded-lg border border-theme">
							{#each teamProfiles as profile}
								<button
									type="button"
									class="hover:bg-theme-hover flex w-full items-center gap-3 px-3 py-2 text-left {formTargetTeamProfileIds.includes(
										profile.id
									)
										? 'bg-accent-50 dark:bg-accent-900/20'
										: ''}"
									onclick={() => toggleTeamProfile(profile.id)}
								>
									<span class="flex-1 text-theme">{profile.fullName}</span>
									{#if formTargetTeamProfileIds.includes(profile.id)}
										<svg class="h-4 w-4 text-accent-500" fill="currentColor" viewBox="0 0 20 20">
											<path
												fill-rule="evenodd"
												d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
												clip-rule="evenodd"
											/>
										</svg>
									{/if}
								</button>
							{/each}
						</div>
					</div>
				{/if}

				<div class="flex justify-end gap-3">
					<button
						type="button"
						class="btn-ghost"
						onclick={() => (showModal = false)}
						disabled={isSubmitting}
					>
						Cancel
					</button>
					<button type="submit" class="btn-primary" disabled={isSubmitting}>
						{isSubmitting ? 'Saving...' : editingRule ? 'Update Rule' : 'Create Rule'}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}
