<script lang="ts">
	import { enhance } from '$app/forms';
	import type { PageData } from './$types';

	interface Props {
		data: PageData;
	}

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

	let searchQuery = $state('');
	let filterRole = $state<'all' | 'admin' | 'user'>('all');
	let isEditModalOpen = $state(false);
	let isSaving = $state(false);
	let saveMessage = $state<{ type: 'success' | 'error'; message: string } | null>(null);

	let editForm = $state<any>({
		id: '',
		name: '',
		email: '',
		isAdmin: false,
		emailVerified: false
	});

	const filteredUsers = $derived.by(() => {
		return data.users.filter((usr) => {
			const matchesSearch =
				usr.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
				usr.email.toLowerCase().includes(searchQuery.toLowerCase());
			const matchesFilter =
				filterRole === 'all' || (filterRole === 'admin' && usr.isAdmin) || (filterRole === 'user' && !usr.isAdmin);
			return matchesSearch && matchesFilter;
		});
	});

	const openEditModal = (usr: any) => {
		editForm = { ...usr };
		isEditModalOpen = true;
		saveMessage = null;
	};

	const closeModal = () => {
		isEditModalOpen = false;
		editForm = {
			id: '',
			name: '',
			email: '',
			isAdmin: false,
			emailVerified: false
		};
		saveMessage = null;
	};

	const handleDeleteUser = async (id: string) => {
		if (!confirm('Are you sure you want to delete this user?')) return;

		try {
			const formData = new FormData();
			formData.append('id', id);

			const response = await fetch('?/delete', {
				method: 'POST',
				body: formData
			});

			if (response.ok) {
				window.location.reload();
			} else {
				alert('Failed to delete user');
			}
		} catch (error) {
			alert('Error deleting user: ' + error);
		}
	};
</script>

<svelte:head>
	<title>Users - Admin - OnePieceDle</title>
</svelte:head>

<div class="space-y-6">
	<!-- Header -->
	<div class="flex items-center justify-between">
		<h2 class="text-3xl font-bold text-white">User Management</h2>
	</div>

	<!-- Filters -->
	<div class="flex flex-col gap-4 rounded-lg border border-white/10 bg-slate-800/50 p-4 md:flex-row md:items-center">
		<input
			type="text"
			placeholder="Search users by name or email..."
			bind:value={searchQuery}
			class="flex-1 rounded-lg bg-slate-700 px-4 py-2 text-sm text-white placeholder-gray-400 outline-none transition focus:ring-2 focus:ring-amber-600"
		/>
		<select
			bind:value={filterRole}
			class="rounded-lg bg-slate-700 px-4 py-2 text-sm text-white outline-none transition focus:ring-2 focus:ring-amber-600"
		>
			<option value="all">All Roles</option>
			<option value="admin">Admin</option>
			<option value="user">User</option>
		</select>
	</div>

	<!-- Users Table -->
	<div class="rounded-lg border border-white/10">
		<div class="max-h-[calc(100vh-20rem)] overflow-auto">
			<table class="w-full">
				<thead class="sticky top-0 bg-slate-800 z-10">
					<tr class="border-b border-white/10">
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Name</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Email</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Role</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Verified</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Joined</th>
						<th class="px-6 py-3 text-left text-sm font-semibold text-gray-300">Actions</th>
					</tr>
				</thead>
				<tbody>
				{#each filteredUsers as usr (usr.id)}
					<tr class="border-b border-white/5 hover:bg-slate-800/50">
						<td class="px-6 py-4 text-sm text-white">{usr.name}</td>
						<td class="px-6 py-4 text-sm text-gray-400">{usr.email}</td>
						<td class="px-6 py-4 text-sm">
							{#if usr.isAdmin}
								<span class="inline-block rounded-full bg-amber-500/20 px-2 py-1 text-xs text-amber-300">
									Admin
								</span>
							{:else}
								<span class="inline-block rounded-full bg-blue-500/20 px-2 py-1 text-xs text-blue-300">
									User
								</span>
							{/if}
						</td>
						<td class="px-6 py-4 text-sm">
							{#if usr.emailVerified}
								<span class="inline-block rounded-full bg-green-500/20 px-2 py-1 text-xs text-green-300">
									✓
								</span>
							{:else}
								<span class="inline-block rounded-full bg-red-500/20 px-2 py-1 text-xs text-red-300">
									✗
								</span>
							{/if}
						</td>
						<td class="px-6 py-4 text-sm text-gray-400">{usr.createdAt}</td>
						<td class="px-6 py-4 text-sm">
							<div class="flex items-center gap-2">
								<button
									onclick={() => openEditModal(usr)}
									class="text-amber-400 hover:text-amber-300 transition-colors"
									title="Edit user"
								>
									<svg class="w-5 h-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"></path></svg>
								</button>
								<button 
									onclick={() => handleDeleteUser(usr.id)}
									class="text-red-400 hover:text-red-300 transition-colors"
									title="Delete user"
								>
									<svg class="w-5 h-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"></path></svg>
								</button>
							</div>
						</td>
					</tr>
				{/each}
				</tbody>
			</table>
		</div>
	</div>

	{#if filteredUsers.length === 0}
		<div class="rounded-lg border border-white/10 bg-slate-800/50 py-12 text-center">
			<p class="text-gray-400">No users found</p>
		</div>
	{/if}

	<!-- Edit Modal -->
	{#if isEditModalOpen}
		<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
			<div class="w-full max-w-md rounded-lg border border-white/10 bg-slate-900 p-6">
				<h3 class="text-lg font-bold text-white">Edit User</h3>
				<form 
					method="POST" 
					action="?/update"
					class="mt-6 space-y-4"
					use:enhance={() => {
						isSaving = true;
						saveMessage = null;
						return async ({ result }) => {
							isSaving = false;
							if (result.type === 'success') {
								saveMessage = { type: 'success', message: 'User updated successfully' };
								setTimeout(() => {
									closeModal();
									window.location.reload();
								}, 500);
							} else if (result.type === 'failure') {
								saveMessage = { type: 'error', message: String(result.data?.error) || 'Failed to update user' };
							}
						};
					}}
				>
					<input type="hidden" name="id" value={editForm.id} />
					<div>
						<label for="user-name" class="block text-sm font-medium text-gray-300">Name</label>
						<input
							id="user-name"
							type="text"
							name="name"
							bind:value={editForm.name}
							class="mt-1 w-full rounded-lg bg-slate-700 px-4 py-2 text-sm text-white outline-none transition focus:ring-2 focus:ring-amber-600"
						/>
					</div>
					<div>
						<label for="user-email" class="block text-sm font-medium text-gray-300">Email</label>
						<input
							id="user-email"
							type="email"
							name="email"
							bind:value={editForm.email}
							class="mt-1 w-full rounded-lg bg-slate-700 px-4 py-2 text-sm text-white outline-none transition focus:ring-2 focus:ring-amber-600"
						/>
					</div>
					<div class="flex items-center gap-2">
						<input
							type="checkbox"
							id="admin-role"
							name="isAdmin"
							bind:checked={editForm.isAdmin}
							class="rounded bg-slate-700"
						/>
						<label for="admin-role" class="text-sm font-medium text-gray-300">Admin Role</label>
					</div>
					<div class="flex items-center gap-2">
						<input
							type="checkbox"
							id="verified"
							name="emailVerified"
							bind:checked={editForm.emailVerified}
							class="rounded bg-slate-700"
						/>
						<label for="verified" class="text-sm font-medium text-gray-300">Email Verified</label>
					</div>
					{#if saveMessage}
						<div class={`rounded-lg p-3 text-sm ${
							saveMessage.type === 'success' 
								? 'bg-green-500/10 text-green-400' 
								: 'bg-red-500/10 text-red-400'
						}`}>
							{saveMessage.message}
						</div>
					{/if}
					<div class="flex gap-3 pt-4">
						<button
							type="button"
							onclick={closeModal}
							disabled={isSaving}
							class="flex-1 rounded-lg border border-gray-500 px-4 py-2 text-sm font-medium text-gray-300 transition-colors hover:bg-slate-700 disabled:opacity-50"
						>
							Cancel
						</button>
						<button
							type="submit"
							disabled={isSaving}
							class="flex-1 rounded-lg bg-amber-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-amber-700 disabled:opacity-50"
						>
							{isSaving ? 'Saving...' : 'Save Changes'}
						</button>
					</div>
				</form>
			</div>
		</div>
	{/if}
</div>
