<script lang="ts">
	import { base } from '$app/paths';
	import { page } from '$app/state';
	import { api, ApiError, type AppUser, type ResetPasswordResponse } from '$lib/api';
	import ConfirmModal from '$lib/ConfirmModal.svelte';

	let slug = $derived(page.params.slug ?? '');
	let users = $state<AppUser[]>([]);
	let nextCursor = $state<string | null>(null);
	let loading = $state(false);
	let error = $state<string | null>(null);

	let showCreate = $state(false);
	let createEmail = $state('');
	let createPassword = $state('');
	let createDisplayName = $state('');
	let creating = $state(false);

	let editing = $state<AppUser | null>(null);
	let editDisplayName = $state('');
	let editRolesText = $state('');
	let savingEdit = $state(false);

	let toRemove = $state<AppUser | null>(null);
	let removing = $state(false);

	let toRevoke = $state<AppUser | null>(null);
	let revoking = $state(false);

	let toReset = $state<AppUser | null>(null);
	let resetToken = $state<ResetPasswordResponse | null>(null);
	let resetting = $state(false);

	async function loadUsers(cursor?: string) {
		loading = true;
		error = null;
		try {
			const res = await api.users.list(slug, { cursor, limit: 100 });
			if (cursor) {
				users = [...users, ...res.users];
			} else {
				users = res.users;
			}
			nextCursor = res.next_cursor;
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			loading = false;
		}
	}

	$effect(() => {
		void slug;
		void loadUsers();
	});

	async function submitCreate() {
		creating = true;
		error = null;
		try {
			const created = await api.users.create(slug, {
				email: createEmail.trim(),
				password: createPassword,
				display_name: createDisplayName.trim() || null
			});
			users = [created, ...users];
			createEmail = '';
			createPassword = '';
			createDisplayName = '';
			showCreate = false;
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			creating = false;
		}
	}

	function openEdit(u: AppUser) {
		editing = u;
		editDisplayName = u.display_name ?? '';
		// Roles are managed via SDK / cron / admin-issued invitations
		// only for v1.1.8; the dashboard renders them read-only here.
		editRolesText = u.roles.join(', ');
	}

	async function submitEdit() {
		if (!editing) return;
		savingEdit = true;
		try {
			const trimmed = editDisplayName.trim();
			const updated = await api.users.patch(slug, editing.id, {
				display_name: trimmed.length ? trimmed : null
			});
			users = users.map((u) => (u.id === updated.id ? updated : u));
			editing = null;
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			savingEdit = false;
		}
	}

	async function confirmRemove() {
		if (!toRemove) return;
		removing = true;
		try {
			await api.users.remove(slug, toRemove.id);
			users = users.filter((u) => u.id !== toRemove!.id);
			toRemove = null;
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			removing = false;
		}
	}

	async function confirmRevoke() {
		if (!toRevoke) return;
		revoking = true;
		try {
			await api.users.revokeSessions(slug, toRevoke.id);
			toRevoke = null;
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			revoking = false;
		}
	}

	async function confirmReset() {
		if (!toReset) return;
		resetting = true;
		try {
			resetToken = await api.users.resetPassword(slug, toReset.id);
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			resetting = false;
		}
	}

	function closeResetTokenModal() {
		toReset = null;
		resetToken = null;
	}

	function fmtTime(iso: string | null): string {
		return iso ? new Date(iso).toLocaleString() : '—';
	}
</script>

<svelte:head>
	<title>Users · {slug} · PiCloud</title>
</svelte:head>

<div class="panel">
	<header class="panel-head">
		<div>
			<h2>Users</h2>
			<p class="subtitle">
				End-users of this app, managed by the <code>users::*</code> SDK. Distinct
				from instance operators (Admins tab).
			</p>
		</div>
		<div class="panel-actions">
			<a class="sublink" href="{base}/apps/{slug}/users/invitations">Invitations →</a>
			<button class="primary" type="button" onclick={() => (showCreate = !showCreate)}>
				{showCreate ? 'Cancel' : 'New user'}
			</button>
		</div>
	</header>

	{#if showCreate}
		<form
			class="create-form"
			onsubmit={(e) => {
				e.preventDefault();
				void submitCreate();
			}}
		>
			<label>
				<span>Email</span>
				<input type="email" required bind:value={createEmail} />
			</label>
			<label>
				<span>Password</span>
				<input type="password" required minlength={8} bind:value={createPassword} />
			</label>
			<label>
				<span>Display name (optional)</span>
				<input type="text" bind:value={createDisplayName} />
			</label>
			<button type="submit" disabled={creating}>
				{creating ? 'Creating…' : 'Create user'}
			</button>
		</form>
	{/if}

	{#if error}
		<div class="error">{error}</div>
	{/if}

	{#if users.length === 0 && !loading}
		<p class="muted">No users yet. Create one above or wait for them to sign up.</p>
	{:else}
		<table>
			<thead>
				<tr>
					<th>Email</th>
					<th>Display name</th>
					<th>Verified</th>
					<th>Roles</th>
					<th>Last login</th>
					<th></th>
				</tr>
			</thead>
			<tbody>
				{#each users as u (u.id)}
					<tr>
						<td>{u.email}</td>
						<td>{u.display_name ?? '—'}</td>
						<td>
							{#if u.email_verified_at}
								<span class="badge badge-ok" title={u.email_verified_at}>yes</span>
							{:else}
								<span class="badge badge-pending">pending</span>
							{/if}
						</td>
						<td>
							{#each u.roles as r}
								<span class="chip">{r}</span>
							{/each}
						</td>
						<td>{fmtTime(u.last_login_at)}</td>
						<td class="row-actions">
							<button type="button" onclick={() => openEdit(u)}>Edit</button>
							<button type="button" onclick={() => (toReset = u)}>Reset pw</button>
							<button type="button" onclick={() => (toRevoke = u)}>Revoke sessions</button>
							<button type="button" class="danger" onclick={() => (toRemove = u)}>
								Delete
							</button>
						</td>
					</tr>
				{/each}
			</tbody>
		</table>
		{#if nextCursor}
			<button
				type="button"
				class="secondary"
				onclick={() => loadUsers(nextCursor ?? undefined)}
			>
				Load more
			</button>
		{/if}
	{/if}
</div>

{#if editing}
	<ConfirmModal
		title="Edit user"
		confirmLabel="Save"
		busy={savingEdit}
		onConfirm={submitEdit}
		onCancel={() => (editing = null)}
	>
		<label class="modal-label">
			<span>Email (immutable)</span>
			<input type="email" value={editing.email} disabled />
		</label>
		<label class="modal-label">
			<span>Display name</span>
			<input type="text" bind:value={editDisplayName} />
		</label>
		<label class="modal-label">
			<span>Roles</span>
			<input type="text" value={editRolesText} disabled />
			<small class="muted">
				Manage via <code>users::add_role</code> / <code>users::remove_role</code> in
				scripts; v1.1.8 does not edit roles from the dashboard.
			</small>
		</label>
	</ConfirmModal>
{/if}

{#if toRemove}
	<ConfirmModal
		title="Delete user"
		variant="danger"
		confirmLabel="Delete user"
		busy={removing}
		onConfirm={confirmRemove}
		onCancel={() => (toRemove = null)}
	>
		<p>
			Delete <strong>{toRemove.email}</strong>? This removes their record, sessions, roles,
			and pending reset / verification tokens. Cannot be undone.
		</p>
	</ConfirmModal>
{/if}

{#if toRevoke}
	<ConfirmModal
		title="Revoke all sessions"
		confirmLabel="Revoke sessions"
		busy={revoking}
		onConfirm={confirmRevoke}
		onCancel={() => (toRevoke = null)}
	>
		<p>
			Revoke every active session for <strong>{toRevoke.email}</strong>? They will be
			signed out everywhere immediately; the next request requires a fresh login.
		</p>
	</ConfirmModal>
{/if}

{#if toReset && !resetToken}
	<ConfirmModal
		title="Generate password-reset token"
		confirmLabel="Generate token"
		busy={resetting}
		onConfirm={confirmReset}
		onCancel={() => (toReset = null)}
	>
		<p>
			Generate a one-shot password-reset token for <strong>{toReset.email}</strong>?
			The token is returned exactly once — paste it into a manual reset link.
		</p>
	</ConfirmModal>
{/if}

{#if resetToken}
	<ConfirmModal
		title="Reset token"
		confirmLabel="Done"
		onConfirm={closeResetTokenModal}
		onCancel={closeResetTokenModal}
	>
		<p>
			Copy this token now — it won't be shown again. It expires in
			{Math.round(resetToken.expires_in_seconds / 60)} minutes.
		</p>
		<pre class="token">{resetToken.token}</pre>
	</ConfirmModal>
{/if}

<style>
	.panel-head {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		gap: 1rem;
		margin-bottom: 1rem;
	}
	.panel-head h2 {
		margin: 0.25rem 0;
		font-size: 1.125rem;
	}
	.subtitle {
		color: var(--text-muted);
		font-size: 0.9rem;
	}
	.panel-actions {
		display: flex;
		align-items: center;
		gap: 0.75rem;
	}
	.sublink {
		color: var(--color-link);
		font-size: 0.875rem;
		text-decoration: none;
	}
	.sublink:hover {
		text-decoration: underline;
	}
	button.primary {
		background: var(--accent);
		color: var(--accent-fg);
		border: none;
		padding: 0.45rem 0.9rem;
		border-radius: var(--radius-md);
		cursor: pointer;
		font-size: 0.875rem;
		font-weight: 600;
	}
	button.primary:hover:not(:disabled) {
		filter: brightness(1.05);
	}
	button.primary:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}
	.create-form {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr auto;
		gap: 0.75rem;
		align-items: end;
		margin-bottom: 1rem;
		padding: 1rem;
		background: var(--bg-elevated);
		border-radius: var(--radius-md);
	}
	.create-form label {
		display: flex;
		flex-direction: column;
		gap: 0.25rem;
		font-size: 0.85rem;
		color: var(--text-muted);
	}
	.create-form input {
		background: var(--bg-secondary);
		color: var(--text-primary);
		border: 1px solid var(--border);
		border-radius: var(--radius-md);
		padding: 0.45rem 0.6rem;
		font: inherit;
	}
	.create-form input:focus {
		outline: none;
		border-color: var(--color-link);
	}
	.modal-label {
		display: flex;
		flex-direction: column;
		gap: 0.25rem;
		font-size: 0.85rem;
		margin-bottom: 0.75rem;
	}
	table {
		width: 100%;
		border-collapse: collapse;
		font-size: 0.9rem;
	}
	th,
	td {
		text-align: left;
		padding: 0.4rem 0.6rem;
		border-bottom: 1px solid var(--border);
	}
	th {
		color: var(--text-muted);
		font-weight: 600;
	}
	.row-actions {
		display: flex;
		gap: 0.25rem;
		flex-wrap: wrap;
	}
	.row-actions button {
		font-size: 0.78rem;
		padding: 0.2rem 0.5rem;
		background: transparent;
		color: var(--text-muted);
		border: 1px solid var(--border);
		border-radius: var(--radius-sm);
		cursor: pointer;
	}
	.row-actions button:hover {
		background: var(--bg-elevated);
		color: var(--text-primary);
	}
	.muted {
		color: var(--text-muted);
	}
	.error {
		color: var(--color-danger);
		margin: 0.5rem 0;
	}
	.row-actions button.danger {
		color: var(--color-danger-fg);
		background: var(--color-danger-bg);
		border-color: var(--color-danger-border);
	}
	.chip {
		display: inline-block;
		padding: 0.1rem 0.4rem;
		border-radius: var(--radius-sm);
		background: var(--bg-elevated);
		color: var(--text-strong);
		font-size: 0.75rem;
		margin-right: 0.25rem;
	}
	.badge {
		display: inline-block;
		padding: 0.1rem 0.4rem;
		border-radius: var(--radius-sm);
		font-size: 0.72rem;
	}
	.badge-ok {
		background: var(--color-success-bg);
		color: var(--color-success-fg);
	}
	.badge-pending {
		background: var(--color-warning-bg);
		color: var(--color-warning-fg);
	}
	.token {
		background: var(--bg-secondary);
		color: var(--text-primary);
		padding: 0.5rem;
		border-radius: var(--radius-sm);
		font-size: 0.85rem;
		overflow-wrap: anywhere;
		white-space: pre-wrap;
		font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
	}
</style>
