<script lang="ts">
	import {
		Users,
		Search,
		Shield,
		ShieldCheck,
		UserCircle,
		Mail,
		Phone,
		Calendar,
		Trash2,
		ChevronDown,
		CheckCircle2,
		Clock,
		XCircle,
		AlertTriangle,
		UserPlus,
		Send
	} from 'lucide-svelte';
	import { Input } from '$lib/components/ui/input';
	import { Button } from '$lib/components/ui/button';
	import { Label } from '$lib/components/ui/label';
	import CountryFlag from '$lib/components/ui/CountryFlag.svelte';
	import { goto, invalidateAll } from '$app/navigation';
	import { page } from '$app/stores';
	import { enhance } from '$app/forms';
	import { onMount } from 'svelte';

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

	// Use $derived to make these reactive when data updates after invalidateAll()
	const members = $derived(data.members);
	const statuses = $derived(data.statuses);
	const stats = $derived(data.stats);
	const filters = $derived(data.filters);

	let searchQuery = $state(filters.search);
	let roleFilter = $state(filters.role);
	let statusFilter = $state(filters.status);
	let memberToDelete = $state<any>(null);
	let showDeleteConfirm = $state(false);
	let showInviteModal = $state(false);
	let inviteLoading = $state(false);
	let inviteEmail = $state('');
	let inviteFirstName = $state('');
	let inviteLastName = $state('');
	let inviteRole = $state('member');

	// Default dues paid date to one year from today
	function getDefaultDuesPaidDate(): string {
		const date = new Date();
		date.setFullYear(date.getFullYear() + 1);
		return date.toISOString().split('T')[0];
	}
	let inviteDuesPaidDate = $state('');

	// Open invite modal with default date
	function openInviteModal() {
		inviteDuesPaidDate = getDefaultDuesPaidDate();
		showInviteModal = true;
	}

	// Close invite modal and reset form on success
	$effect(() => {
		if (form?.success && form.success.includes('Invitation sent')) {
			showInviteModal = false;
			inviteEmail = '';
			inviteFirstName = '';
			inviteLastName = '';
			inviteRole = 'member';
			inviteDuesPaidDate = getDefaultDuesPaidDate();
		}
	});

	// Close delete modal on success
	$effect(() => {
		if (form?.success && form.success.includes('deleted')) {
			showDeleteConfirm = false;
			memberToDelete = null;
		}
	});

	// Debounce search
	let searchTimeout: ReturnType<typeof setTimeout>;
	function handleSearch(value: string) {
		clearTimeout(searchTimeout);
		searchTimeout = setTimeout(() => {
			updateFilters({ search: value });
		}, 300);
	}

	function updateFilters(newFilters: Record<string, string>) {
		const params = new URLSearchParams($page.url.searchParams);
		for (const [key, value] of Object.entries(newFilters)) {
			if (value && value !== 'all') {
				params.set(key, value);
			} else {
				params.delete(key);
			}
		}
		goto(`?${params.toString()}`, { replaceState: true });
	}

	function confirmDelete(member: any) {
		memberToDelete = member;
		showDeleteConfirm = true;
	}

	// Format date
	function formatDate(dateStr: string | null): string {
		if (!dateStr) return 'N/A';
		return new Date(dateStr).toLocaleDateString('en-US', {
			year: 'numeric',
			month: 'short',
			day: 'numeric'
		});
	}

	// Get role info
	function getRoleInfo(role: string) {
		switch (role) {
			case 'admin':
				return { icon: ShieldCheck, color: 'text-purple-600', bg: 'bg-purple-100', label: 'Admin' };
			case 'board':
				return { icon: Shield, color: 'text-blue-600', bg: 'bg-blue-100', label: 'Board' };
			default:
				return { icon: UserCircle, color: 'text-slate-600', bg: 'bg-slate-100', label: 'Member' };
		}
	}

	// Get status info
	function getStatusInfo(status: string | null) {
		switch (status) {
			case 'active':
				return { icon: CheckCircle2, color: 'text-green-600', bg: 'bg-green-100' };
			case 'pending':
				return { icon: Clock, color: 'text-yellow-600', bg: 'bg-yellow-100' };
			case 'inactive':
				return { icon: XCircle, color: 'text-slate-500', bg: 'bg-slate-100' };
			case 'expired':
				return { icon: AlertTriangle, color: 'text-red-600', bg: 'bg-red-100' };
			default:
				return { icon: UserCircle, color: 'text-slate-500', bg: 'bg-slate-100' };
		}
	}
</script>

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

<div class="space-y-6">
	<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
		<div>
			<h1 class="text-2xl font-bold text-slate-900">User Management</h1>
			<p class="text-slate-500">Manage member accounts, roles, and statuses</p>
		</div>
		<Button variant="monaco" onclick={openInviteModal}>
			<UserPlus class="mr-2 h-4 w-4" />
			Invite Member
		</Button>
	</div>

	{#if form?.error}
		<div class="rounded-lg bg-red-50 p-4 text-sm text-red-600">
			{form.error}
		</div>
	{/if}

	{#if form?.success}
		<div class="rounded-lg bg-green-50 p-4 text-sm text-green-600">
			{form.success}
		</div>
	{/if}

	<!-- Stats Cards -->
	<div class="grid grid-cols-2 gap-4 sm:grid-cols-4">
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-slate-100 p-2">
					<Users class="h-5 w-5 text-slate-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.total}</p>
					<p class="text-xs text-slate-500">Total Users</p>
				</div>
			</div>
		</div>
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-purple-100 p-2">
					<ShieldCheck class="h-5 w-5 text-purple-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.admins}</p>
					<p class="text-xs text-slate-500">Admins</p>
				</div>
			</div>
		</div>
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-blue-100 p-2">
					<Shield class="h-5 w-5 text-blue-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.board}</p>
					<p class="text-xs text-slate-500">Board Members</p>
				</div>
			</div>
		</div>
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-slate-100 p-2">
					<UserCircle class="h-5 w-5 text-slate-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.members}</p>
					<p class="text-xs text-slate-500">Members</p>
				</div>
			</div>
		</div>
	</div>

	<!-- Filters -->
	<div class="glass-card p-4">
		<div class="flex flex-col gap-4 sm:flex-row sm:items-center">
			<div class="relative flex-1">
				<Search class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
				<Input
					type="search"
					placeholder="Search by name, email, or member ID..."
					value={searchQuery}
					oninput={(e) => {
						searchQuery = e.currentTarget.value;
						handleSearch(e.currentTarget.value);
					}}
					class="h-10 pl-9"
				/>
			</div>

			<select
				bind:value={roleFilter}
				onchange={() => updateFilters({ role: roleFilter })}
				class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
			>
				<option value="all">All Roles</option>
				<option value="admin">Admin</option>
				<option value="board">Board</option>
				<option value="member">Member</option>
			</select>

			<select
				bind:value={statusFilter}
				onchange={() => updateFilters({ status: statusFilter })}
				class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
			>
				<option value="all">All Statuses</option>
				{#each statuses as status}
					<option value={status.name}>{status.display_name}</option>
				{/each}
			</select>
		</div>
	</div>

	<!-- Members Table -->
	<div class="glass-card overflow-hidden">
		{#if members.length === 0}
			<div class="flex flex-col items-center justify-center p-12 text-center">
				<Users class="mb-4 h-16 w-16 text-slate-300" />
				<h3 class="text-lg font-medium text-slate-900">No users found</h3>
				<p class="mt-1 text-slate-500">Try adjusting your search or filters.</p>
			</div>
		{:else}
			<div class="overflow-x-auto">
				<table class="w-full">
					<thead class="bg-slate-50">
						<tr>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">User</th>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">Contact</th>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">Role</th>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">Status</th>
							<th class="px-6 py-3 text-left text-xs font-medium uppercase text-slate-500">Joined</th>
							<th class="px-6 py-3 text-right text-xs font-medium uppercase text-slate-500">Actions</th>
						</tr>
					</thead>
					<tbody class="divide-y divide-slate-100">
						{#each members as member}
							{@const roleInfo = getRoleInfo(member.role)}
							{@const statusInfo = getStatusInfo(member.status_name)}
							<tr class="hover:bg-slate-50">
								<td class="px-6 py-4">
									<div class="flex items-center gap-3">
										{#if member.avatar_url}
											<img
												src={member.avatar_url}
												alt=""
												class="h-10 w-10 rounded-full object-cover"
											/>
										{:else}
											<div
												class="flex h-10 w-10 items-center justify-center rounded-full bg-monaco-100 text-monaco-700"
											>
												{member.first_name?.[0]}{member.last_name?.[0]}
											</div>
										{/if}
										<div>
											<div class="flex items-center gap-2">
												<p class="font-medium text-slate-900">
													{member.first_name} {member.last_name}
												</p>
												{#if member.nationality && member.nationality.length > 0}
													<div class="flex items-center gap-0.5">
														{#each member.nationality as code}
															<CountryFlag {code} size="xs" />
														{/each}
													</div>
												{/if}
											</div>
											<p class="text-xs text-slate-500">{member.member_id}</p>
										</div>
									</div>
								</td>
								<td class="px-6 py-4">
									<div class="space-y-1">
										<div class="flex items-center gap-1.5 text-sm text-slate-600">
											<Mail class="h-3.5 w-3.5" />
											{member.email}
										</div>
										{#if member.phone}
											<div class="flex items-center gap-1.5 text-sm text-slate-500">
												<Phone class="h-3.5 w-3.5" />
												{member.phone}
											</div>
										{/if}
									</div>
								</td>
								<td class="px-6 py-4">
									<form
										method="POST"
										action="?/updateRole"
										use:enhance={() => {
											return async ({ update }) => {
												await invalidateAll();
												await update();
											};
										}}
										class="inline"
									>
										<input type="hidden" name="member_id" value={member.id} />
										<select
											name="role"
											value={member.role}
											onchange={(e) => e.currentTarget.form?.requestSubmit()}
											class="rounded-lg border-0 bg-transparent py-1 pr-8 text-sm font-medium {roleInfo.color} cursor-pointer hover:bg-slate-100"
										>
											<option value="member">Member</option>
											<option value="board">Board</option>
											<option value="admin">Admin</option>
										</select>
									</form>
								</td>
								<td class="px-6 py-4">
									<form
										method="POST"
										action="?/updateStatus"
										use:enhance={() => {
											return async ({ update }) => {
												await invalidateAll();
												await update();
											};
										}}
										class="inline"
									>
										<input type="hidden" name="member_id" value={member.id} />
										<select
											name="status_id"
											value={member.membership_status_id || ''}
											onchange={(e) => e.currentTarget.form?.requestSubmit()}
											class="rounded-lg border-0 bg-transparent py-1 pr-8 text-sm cursor-pointer hover:bg-slate-100"
										>
											{#each statuses as status}
												<option value={status.id}>{status.display_name}</option>
											{/each}
										</select>
									</form>
								</td>
								<td class="px-6 py-4 text-sm text-slate-500">
									{formatDate(member.member_since)}
								</td>
								<td class="px-6 py-4 text-right">
									<button
										onclick={() => confirmDelete(member)}
										class="rounded p-1.5 text-slate-400 hover:bg-red-100 hover:text-red-600"
										title="Delete Member"
									>
										<Trash2 class="h-4 w-4" />
									</button>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		{/if}
	</div>
</div>

<!-- Delete Confirmation Modal -->
{#if showDeleteConfirm && memberToDelete}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-4 flex items-center gap-3 text-red-600">
				<AlertTriangle class="h-6 w-6" />
				<h3 class="text-lg font-semibold">Delete Member</h3>
			</div>

			<p class="mb-4 text-slate-600">
				Are you sure you want to delete <strong>{memberToDelete.first_name} {memberToDelete.last_name}</strong>
				({memberToDelete.member_id})? This action cannot be undone.
			</p>

			<p class="mb-6 text-sm text-slate-500">
				This will permanently delete their account, payment history, and all associated data.
			</p>

			<div class="flex gap-3">
				<button
					onclick={() => {
						showDeleteConfirm = false;
						memberToDelete = null;
					}}
					class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
				>
					Cancel
				</button>
				<form
					method="POST"
					action="?/deleteMember"
					use:enhance={() => {
						return async ({ update, result }) => {
							if (result.type === 'success') {
								showDeleteConfirm = false;
								memberToDelete = null;
								await invalidateAll();
							}
							await update();
						};
					}}
					class="flex-1"
				>
					<input type="hidden" name="member_id" value={memberToDelete.id} />
					<button
						type="submit"
						class="w-full rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700"
					>
						Delete Member
					</button>
				</form>
			</div>
		</div>
	</div>
{/if}

<!-- Invite Member Modal -->
{#if showInviteModal}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-4 flex items-center gap-3 text-monaco-600">
				<UserPlus class="h-6 w-6" />
				<h3 class="text-lg font-semibold text-slate-900">Invite New Member</h3>
			</div>

			<p class="mb-6 text-sm text-slate-600">
				Send an invitation email to a new member. They will receive instructions to set up their account.
			</p>

			<form
				method="POST"
				action="?/inviteMember"
				use:enhance={() => {
					inviteLoading = true;
					return async ({ update, result }) => {
						inviteLoading = false;
						if (result.type === 'success') {
							await invalidateAll();
						}
						await update();
					};
				}}
				class="space-y-4"
			>
				<div class="space-y-2">
					<Label for="invite_email">Email Address *</Label>
					<Input
						id="invite_email"
						name="email"
						type="email"
						placeholder="member@example.com"
						bind:value={inviteEmail}
						required
						disabled={inviteLoading}
						class="h-11"
					/>
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="invite_first_name">First Name</Label>
						<Input
							id="invite_first_name"
							name="first_name"
							type="text"
							placeholder="John"
							bind:value={inviteFirstName}
							disabled={inviteLoading}
							class="h-11"
						/>
					</div>
					<div class="space-y-2">
						<Label for="invite_last_name">Last Name</Label>
						<Input
							id="invite_last_name"
							name="last_name"
							type="text"
							placeholder="Doe"
							bind:value={inviteLastName}
							disabled={inviteLoading}
							class="h-11"
						/>
					</div>
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="space-y-2">
						<Label for="invite_role">Role</Label>
						<select
							id="invite_role"
							name="role"
							bind:value={inviteRole}
							disabled={inviteLoading}
							class="h-11 w-full rounded-md border border-slate-200 bg-white px-3 text-sm focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
						>
							<option value="member">Member</option>
							<option value="board">Board</option>
							<option value="admin">Admin</option>
						</select>
					</div>
					<div class="space-y-2">
						<Label for="invite_dues_paid_date">Dues Paid Until</Label>
						<input
							id="invite_dues_paid_date"
							name="dues_paid_date"
							type="date"
							value={inviteDuesPaidDate}
							oninput={(e) => inviteDuesPaidDate = e.currentTarget.value}
							disabled={inviteLoading}
							class="h-11 w-full rounded-md border border-slate-200 bg-white px-3 text-sm focus:border-monaco-500 focus:outline-none focus:ring-1 focus:ring-monaco-500"
						/>
					</div>
				</div>

				<p class="text-xs text-slate-500">
					* Required field. Other fields are optional - the member can update their profile after joining.
				</p>

				<div class="flex gap-3 pt-2">
					<Button
						type="button"
						variant="outline"
						onclick={() => {
							showInviteModal = false;
							inviteEmail = '';
							inviteFirstName = '';
							inviteLastName = '';
							inviteRole = 'member';
							inviteDuesPaidDate = getDefaultDuesPaidDate();
						}}
						disabled={inviteLoading}
						class="flex-1"
					>
						Cancel
					</Button>
					<Button type="submit" variant="monaco" disabled={inviteLoading || !inviteEmail} class="flex-1">
						{#if inviteLoading}
							<span class="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"></span>
							Sending...
						{:else}
							<Send class="mr-2 h-4 w-4" />
							Send Invitation
						{/if}
					</Button>
				</div>
			</form>
		</div>
	</div>
{/if}
