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

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

	let search = $state('');
	let showForm = $state(false);

	const filtered = $derived(
		data.users.filter(
			(u) =>
				u.nama.toLowerCase().includes(search.toLowerCase()) ||
				u.email.toLowerCase().includes(search.toLowerCase()) ||
				data.roleLabels[u.role].toLowerCase().includes(search.toLowerCase())
		)
	);

	function roleBadgeClass(role: string): string {
		if (role === 'super_admin') return 'badge-error';
		if (role === 'admin') return 'badge-primary';
		return 'badge-ghost';
	}
</script>

<svelte:head>
	<title>Back Office — Pengguna</title>
</svelte:head>

<div class="page-content">
	<div class="flex flex-wrap items-start justify-between gap-4">
		<div>
			<h1 class="text-2xl font-bold">Kelola Pengguna Back Office</h1>
			<p class="text-sm text-base-content/50">
				Tambah staf, atur role, dan kelola akses panel administrator.
			</p>
		</div>
		<button type="button" class="btn btn-primary btn-sm" onclick={() => (showForm = !showForm)}>
			{showForm ? 'Tutup Form' : '+ Tambah Pengguna'}
		</button>
	</div>

	<div class="mt-4 grid gap-3 sm:grid-cols-3">
		{#each data.roles as role}
			<div class="rounded-xl border border-base-300 bg-base-100 p-4">
				<p class="font-semibold">{data.roleLabels[role]}</p>
				<p class="mt-1 text-xs text-base-content/60">{data.roleDescriptions[role]}</p>
			</div>
		{/each}
	</div>

	{#if form?.error}
		<div class="alert alert-error mt-4">
			<span>{form.error}</span>
		</div>
	{/if}

	{#if showForm}
		<div class="card mt-6 max-w-2xl bg-base-100 shadow-md">
			<div class="card-body gap-6">
				<div class="border-b border-base-300/60 pb-3">
					<h2 class="text-lg font-bold">Tambah Pengguna Baru</h2>
				</div>
				<form method="POST" action="?/create" use:enhance class="space-y-5">
					<div class="flex flex-col gap-2">
						<label for="create-nama" class="text-sm font-semibold">Nama lengkap</label>
						<input
							id="create-nama"
							type="text"
							name="nama"
							class="input input-bordered w-full {form?.field === 'nama' ? 'input-error' : ''}"
							required
							minlength="2"
						/>
					</div>
					<div class="flex flex-col gap-2">
						<label for="create-email" class="text-sm font-semibold">Email</label>
						<input
							id="create-email"
							type="email"
							name="email"
							class="input input-bordered w-full {form?.field === 'email' ? 'input-error' : ''}"
							required
						/>
					</div>
					<div class="flex flex-col gap-2">
						<label for="create-password" class="text-sm font-semibold">Password</label>
						<input
							id="create-password"
							type="password"
							name="password"
							class="input input-bordered w-full {form?.field === 'password' ? 'input-error' : ''}"
							required
							minlength="6"
							autocomplete="new-password"
						/>
						<p class="text-xs text-base-content/50">Minimal 6 karakter.</p>
					</div>
					<div class="flex flex-col gap-2">
						<label for="create-role" class="text-sm font-semibold">Role</label>
						<select
							id="create-role"
							name="role"
							class="select select-bordered w-full {form?.field === 'role' ? 'select-error' : ''}"
						>
							{#each data.roles as role}
								<option value={role}>{data.roleLabels[role]}</option>
							{/each}
						</select>
					</div>
					<div class="border-t border-base-300/60 pt-4">
						<button type="submit" class="btn btn-primary">Simpan Pengguna</button>
					</div>
				</form>
			</div>
		</div>
	{/if}

	<div class="mt-6">
		<input
			type="search"
			class="input input-bordered w-full max-w-md"
			placeholder="Cari nama, email, atau role..."
			bind:value={search}
		/>
	</div>

	<div class="mt-6 overflow-x-auto rounded-xl bg-base-100 shadow">
		<table class="table">
			<thead>
				<tr>
					<th>Pengguna</th>
					<th>Role</th>
					<th>Status</th>
					<th>Dibuat</th>
					<th></th>
				</tr>
			</thead>
			<tbody>
				{#each filtered as user}
					<tr class={user.id === data.currentUserId ? 'bg-primary/5' : ''}>
						<td>
							<p class="font-medium">
								{user.nama}
								{#if user.id === data.currentUserId}
									<span class="badge badge-outline badge-xs ml-1">Anda</span>
								{/if}
							</p>
							<p class="text-xs text-base-content/50">{user.email}</p>
						</td>
						<td>
							<span class="badge badge-sm {roleBadgeClass(user.role)}">
								{data.roleLabels[user.role]}
							</span>
						</td>
						<td>
							{#if user.is_aktif}
								<span class="badge badge-success badge-sm">Aktif</span>
							{:else}
								<span class="badge badge-warning badge-sm">Nonaktif</span>
							{/if}
						</td>
						<td class="text-sm text-base-content/60">
							{new Date(user.created_at).toLocaleDateString('id-ID')}
						</td>
						<td>
							<a href="/backoffice/users/{user.id}" class="btn btn-ghost btn-sm">Kelola</a>
						</td>
					</tr>
				{:else}
					<tr>
						<td colspan="5" class="text-center text-base-content/50">Tidak ada pengguna ditemukan</td>
					</tr>
				{/each}
			</tbody>
		</table>
	</div>
</div>
