<script lang="ts">
	import { enhance } from '$app/forms';
	import { Bell, Send, Trash2, Users, Calendar, CreditCard, Megaphone, Settings, ChevronDown, X, Check, AlertCircle } from 'lucide-svelte';

	interface Member {
		id: string;
		first_name: string;
		last_name: string;
		email: string;
		role: string;
	}

	interface Notification {
		id: string;
		type: string;
		title: string;
		message: string;
		link: string | null;
		read_at: string | null;
		created_at: string;
		member: Member | null;
	}

	let { data, form } = $props();

	let recipientType = $state<'all' | 'role' | 'single'>('all');
	let selectedRole = $state('member');
	let selectedMemberId = $state('');
	let showCreateForm = $state(false);
	let submitting = $state(false);

	const notificationTypes = [
		{ value: 'announcement', label: 'Announcement', icon: Megaphone, color: 'text-monaco-600 bg-monaco-100' },
		{ value: 'event', label: 'Event', icon: Calendar, color: 'text-blue-600 bg-blue-100' },
		{ value: 'payment', label: 'Payment', icon: CreditCard, color: 'text-amber-600 bg-amber-100' },
		{ value: 'membership', label: 'Membership', icon: Users, color: 'text-purple-600 bg-purple-100' },
		{ value: 'system', label: 'System', icon: Settings, color: 'text-slate-600 bg-slate-100' }
	];

	function getTypeInfo(type: string) {
		return notificationTypes.find(t => t.value === type) || notificationTypes[4];
	}

	function formatDate(dateString: string) {
		return new Date(dateString).toLocaleDateString('en-US', {
			year: 'numeric',
			month: 'short',
			day: 'numeric',
			hour: '2-digit',
			minute: '2-digit'
		});
	}

	function getRecipientCount() {
		if (recipientType === 'all') return data.members.length;
		if (recipientType === 'role') return data.members.filter((m: Member) => m.role === selectedRole).length;
		if (recipientType === 'single' && selectedMemberId) return 1;
		return 0;
	}
</script>

<svelte:head>
	<title>Notifications Management | Monaco USA Admin</title>
</svelte:head>

<div class="max-w-6xl mx-auto">
	<!-- Header -->
	<div class="mb-8 flex items-center justify-between">
		<div>
			<h1 class="text-2xl font-bold text-slate-900">Notification Management</h1>
			<p class="mt-1 text-slate-600">Send notifications to members and view notification history</p>
		</div>
		<button
			onclick={() => showCreateForm = !showCreateForm}
			class="flex items-center gap-2 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 transition-colors"
		>
			{#if showCreateForm}
				<X class="h-4 w-4" />
				Cancel
			{:else}
				<Send class="h-4 w-4" />
				Send Notification
			{/if}
		</button>
	</div>

	<!-- Success/Error Messages -->
	{#if form?.success}
		<div class="mb-6 rounded-lg border border-green-200 bg-green-50 p-4 flex items-center gap-3">
			<Check class="h-5 w-5 text-green-600" />
			<p class="text-green-800">{form.success}</p>
		</div>
	{/if}
	{#if form?.error}
		<div class="mb-6 rounded-lg border border-red-200 bg-red-50 p-4 flex items-center gap-3">
			<AlertCircle class="h-5 w-5 text-red-600" />
			<p class="text-red-800">{form.error}</p>
		</div>
	{/if}

	<!-- Create Notification Form -->
	{#if showCreateForm}
		<div class="mb-8 rounded-xl border border-slate-200 bg-white p-6">
			<h2 class="text-lg font-semibold text-slate-900 mb-6">Create New Notification</h2>

			<form
				method="POST"
				action="?/create"
				use:enhance={() => {
					submitting = true;
					return async ({ update }) => {
						await update();
						submitting = false;
						if (form?.success) {
							showCreateForm = false;
						}
					};
				}}
				class="space-y-6"
			>
				<!-- Notification Type -->
				<div>
					<label class="block text-sm font-medium text-slate-700 mb-2">Notification Type</label>
					<div class="grid grid-cols-2 sm:grid-cols-5 gap-3">
						{#each notificationTypes as type}
							{@const Icon = type.icon}
							<label class="relative">
								<input type="radio" name="type" value={type.value} class="peer sr-only" required />
								<div class="flex flex-col items-center gap-2 rounded-lg border-2 border-slate-200 p-3 cursor-pointer transition-all peer-checked:border-monaco-600 peer-checked:bg-monaco-50 hover:border-slate-300">
									<div class="rounded-full p-2 {type.color}">
										<Icon class="h-4 w-4" />
									</div>
									<span class="text-sm font-medium text-slate-700">{type.label}</span>
								</div>
							</label>
						{/each}
					</div>
				</div>

				<!-- Title -->
				<div>
					<label for="title" class="block text-sm font-medium text-slate-700 mb-2">Title</label>
					<input
						type="text"
						id="title"
						name="title"
						required
						maxlength="100"
						placeholder="e.g., New Event Announcement"
						class="w-full rounded-lg border border-slate-300 px-4 py-2 focus:border-monaco-500 focus:ring-2 focus:ring-monaco-500/20 outline-none"
					/>
				</div>

				<!-- Message -->
				<div>
					<label for="message" class="block text-sm font-medium text-slate-700 mb-2">Message</label>
					<textarea
						id="message"
						name="message"
						required
						rows="3"
						maxlength="500"
						placeholder="Enter the notification message..."
						class="w-full rounded-lg border border-slate-300 px-4 py-2 focus:border-monaco-500 focus:ring-2 focus:ring-monaco-500/20 outline-none resize-none"
					></textarea>
				</div>

				<!-- Link (optional) -->
				<div>
					<label for="link" class="block text-sm font-medium text-slate-700 mb-2">
						Link (optional)
					</label>
					<input
						type="text"
						id="link"
						name="link"
						placeholder="/events or /profile"
						class="w-full rounded-lg border border-slate-300 px-4 py-2 focus:border-monaco-500 focus:ring-2 focus:ring-monaco-500/20 outline-none"
					/>
					<p class="mt-1 text-xs text-slate-500">Users will be redirected here when they click the notification</p>
				</div>

				<!-- Recipients -->
				<div>
					<label class="block text-sm font-medium text-slate-700 mb-2">Recipients</label>
					<div class="space-y-3">
						<!-- All Members -->
						<label class="flex items-center gap-3 rounded-lg border border-slate-200 p-3 cursor-pointer hover:bg-slate-50 has-[:checked]:border-monaco-600 has-[:checked]:bg-monaco-50">
							<input
								type="radio"
								name="recipient_type"
								value="all"
								bind:group={recipientType}
								class="text-monaco-600 focus:ring-monaco-500"
							/>
							<div class="flex-1">
								<span class="font-medium text-slate-900">All Members</span>
								<span class="ml-2 text-sm text-slate-500">({data.members.length} members)</span>
							</div>
						</label>

						<!-- By Role -->
						<label class="flex items-center gap-3 rounded-lg border border-slate-200 p-3 cursor-pointer hover:bg-slate-50 has-[:checked]:border-monaco-600 has-[:checked]:bg-monaco-50">
							<input
								type="radio"
								name="recipient_type"
								value="role"
								bind:group={recipientType}
								class="text-monaco-600 focus:ring-monaco-500"
							/>
							<div class="flex-1">
								<span class="font-medium text-slate-900">By Role</span>
							</div>
						</label>
						{#if recipientType === 'role'}
							<div class="ml-8">
								<select
									name="role"
									bind:value={selectedRole}
									class="rounded-lg border border-slate-300 px-4 py-2 focus:border-monaco-500 focus:ring-2 focus:ring-monaco-500/20 outline-none"
								>
									<option value="member">Members ({data.members.filter((m: Member) => m.role === 'member').length})</option>
									<option value="board">Board Members ({data.members.filter((m: Member) => m.role === 'board').length})</option>
									<option value="admin">Admins ({data.members.filter((m: Member) => m.role === 'admin').length})</option>
								</select>
							</div>
						{/if}

						<!-- Single Member -->
						<label class="flex items-center gap-3 rounded-lg border border-slate-200 p-3 cursor-pointer hover:bg-slate-50 has-[:checked]:border-monaco-600 has-[:checked]:bg-monaco-50">
							<input
								type="radio"
								name="recipient_type"
								value="single"
								bind:group={recipientType}
								class="text-monaco-600 focus:ring-monaco-500"
							/>
							<div class="flex-1">
								<span class="font-medium text-slate-900">Single Member</span>
							</div>
						</label>
						{#if recipientType === 'single'}
							<div class="ml-8">
								<select
									name="recipient_id"
									bind:value={selectedMemberId}
									required={recipientType === 'single'}
									class="w-full rounded-lg border border-slate-300 px-4 py-2 focus:border-monaco-500 focus:ring-2 focus:ring-monaco-500/20 outline-none"
								>
									<option value="">Select a member...</option>
									{#each data.members as m}
										<option value={m.id}>{m.first_name} {m.last_name} ({m.email})</option>
									{/each}
								</select>
							</div>
						{/if}
					</div>
				</div>

				<!-- Submit -->
				<div class="flex items-center justify-between pt-4 border-t border-slate-100">
					<p class="text-sm text-slate-600">
						This will send a notification to <strong>{getRecipientCount()}</strong> member{getRecipientCount() === 1 ? '' : 's'}
					</p>
					<button
						type="submit"
						disabled={submitting || getRecipientCount() === 0}
						class="flex items-center gap-2 rounded-lg bg-monaco-600 px-6 py-2 font-medium text-white hover:bg-monaco-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
					>
						{#if submitting}
							<div class="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"></div>
						{:else}
							<Send class="h-4 w-4" />
						{/if}
						Send Notification
					</button>
				</div>
			</form>
		</div>
	{/if}

	<!-- Recent Notifications -->
	<div class="rounded-xl border border-slate-200 bg-white">
		<div class="border-b border-slate-100 px-6 py-4">
			<h2 class="text-lg font-semibold text-slate-900">Recent Notifications</h2>
			<p class="text-sm text-slate-500">Last 100 notifications sent</p>
		</div>

		{#if data.notifications.length === 0}
			<div class="p-12 text-center">
				<Bell class="mx-auto h-12 w-12 text-slate-300" />
				<h3 class="mt-4 text-lg font-medium text-slate-900">No notifications yet</h3>
				<p class="mt-2 text-slate-600">Create your first notification above</p>
			</div>
		{:else}
			<div class="divide-y divide-slate-100">
				{#each data.notifications as notification}
					{@const typeInfo = getTypeInfo(notification.type)}
					{@const Icon = typeInfo.icon}
					<div class="flex items-start gap-4 px-6 py-4 hover:bg-slate-50">
						<div class="flex-shrink-0 rounded-full p-2 {typeInfo.color}">
							<Icon class="h-4 w-4" />
						</div>
						<div class="min-w-0 flex-1">
							<div class="flex items-start justify-between gap-4">
								<div>
									<p class="font-medium text-slate-900">{notification.title}</p>
									<p class="mt-0.5 text-sm text-slate-600 line-clamp-2">{notification.message}</p>
									<div class="mt-2 flex items-center gap-3 text-xs text-slate-500">
										<span>
											To: {notification.member ? `${notification.member.first_name} ${notification.member.last_name}` : 'Unknown'}
										</span>
										<span>&bull;</span>
										<span>{formatDate(notification.created_at)}</span>
										{#if notification.read_at}
											<span class="inline-flex items-center gap-1 text-green-600">
												<Check class="h-3 w-3" />
												Read
											</span>
										{:else}
											<span class="text-amber-600">Unread</span>
										{/if}
									</div>
								</div>
								<form method="POST" action="?/delete" use:enhance>
									<input type="hidden" name="id" value={notification.id} />
									<button
										type="submit"
										class="rounded-lg p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors"
										title="Delete notification"
									>
										<Trash2 class="h-4 w-4" />
									</button>
								</form>
							</div>
						</div>
					</div>
				{/each}
			</div>
		{/if}
	</div>
</div>
