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

	let slug = $derived(page.params.slug ?? '');
	let app = $state<App | null>(null);
	let invitations = $state<Invitation[]>([]);
	let loading = $state(false);
	let error = $state<string | null>(null);

	let showCreate = $state(false);
	let createEmail = $state('');
	let createDisplayName = $state('');
	let createRoles = $state('');
	let sendEmail = $state(false);
	let templateLinkBase = $state('');
	let templateFrom = $state('');
	let templateSubject = $state('You have been invited');
	let templateBody = $state(
		"Welcome — click the link below to set up your account.\n\n{link}"
	);
	let creating = $state(false);

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

	async function loadApp() {
		try {
			app = await api.apps.get(slug);
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		}
	}

	async function loadInvitations() {
		loading = true;
		error = null;
		try {
			const res = await api.appInvitations.list(slug);
			invitations = res.invitations;
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			loading = false;
		}
	}

	$effect(() => {
		void slug;
		void loadApp();
		void loadInvitations();
	});

	async function submitCreate() {
		creating = true;
		error = null;
		try {
			const roles = createRoles
				.split(',')
				.map((s) => s.trim())
				.filter((s) => s.length > 0);
			const template = sendEmail
				? {
						link_base: templateLinkBase.trim(),
						from: templateFrom.trim(),
						subject: templateSubject,
						body_template: templateBody
					}
				: undefined;
			const created = await api.appInvitations.create(slug, {
				email: createEmail.trim(),
				display_name: createDisplayName.trim() || null,
				roles,
				template
			});
			invitations = [created, ...invitations];
			createEmail = '';
			createDisplayName = '';
			createRoles = '';
			showCreate = false;
		} catch (e) {
			error = e instanceof ApiError ? e.message : String(e);
		} finally {
			creating = false;
		}
	}

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

	function fmtTime(iso: string): string {
		return new Date(iso).toLocaleString();
	}
</script>

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

<div class="panel">
	<header class="panel-head">
		<div>
			<a href="{base}/apps/{slug}/users" class="back">&larr; Users</a>
			<h2>Invitations</h2>
			<p class="subtitle">
				Pending invitations. Accepting an invitation creates the user and signs them in
				with a fresh session token; pre-staged roles are applied atomically.
			</p>
		</div>
		<div>
			<button class="primary" type="button" onclick={() => (showCreate = !showCreate)}>
				{showCreate ? 'Cancel' : 'New invitation'}
			</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>Display name (optional)</span>
				<input type="text" bind:value={createDisplayName} />
			</label>
			<label>
				<span>Roles (comma-separated, optional)</span>
				<input type="text" bind:value={createRoles} placeholder="editor, admin" />
			</label>

			<label class="checkbox-row">
				<input type="checkbox" bind:checked={sendEmail} />
				<span>Send invitation email</span>
				<small class="muted">
					Off = generate token only (out-of-band delivery). Requires SMTP configured.
				</small>
			</label>

			{#if sendEmail}
				<label>
					<span>Link base</span>
					<input
						type="url"
						required
						bind:value={templateLinkBase}
						placeholder="https://app.example.com/accept-invite"
					/>
				</label>
				<label>
					<span>From</span>
					<input
						type="email"
						required
						bind:value={templateFrom}
						placeholder="invites@app.example.com"
					/>
				</label>
				<label>
					<span>Subject</span>
					<input type="text" required bind:value={templateSubject} />
				</label>
				<label class="full-row">
					<span>Body template (use <code>{'{link}'}</code> placeholder)</span>
					<textarea rows={5} bind:value={templateBody}></textarea>
				</label>
			{/if}

			<button type="submit" disabled={creating} class="full-row">
				{creating ? 'Creating…' : 'Create invitation'}
			</button>
		</form>
	{/if}

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

	{#if loading}
		<p class="muted">Loading…</p>
	{:else if invitations.length === 0}
		<p class="muted">No pending invitations.</p>
	{:else}
		<table>
			<thead>
				<tr>
					<th>Email</th>
					<th>Display name</th>
					<th>Roles</th>
					<th>Created</th>
					<th>Expires</th>
					<th></th>
				</tr>
			</thead>
			<tbody>
				{#each invitations as inv (inv.id)}
					<tr>
						<td>{inv.email}</td>
						<td>{inv.display_name ?? '—'}</td>
						<td>
							{#each inv.roles as r}
								<span class="chip">{r}</span>
							{/each}
						</td>
						<td>{fmtTime(inv.created_at)}</td>
						<td>{fmtTime(inv.expires_at)}</td>
						<td>
							<button type="button" class="danger" onclick={() => (toRevoke = inv)}>
								Revoke
							</button>
						</td>
					</tr>
				{/each}
			</tbody>
		</table>
	{/if}
</div>

{#if toRevoke}
	<ConfirmModal
		title="Revoke invitation"
		variant="danger"
		confirmLabel="Revoke"
		busy={revoking}
		onConfirm={confirmRevoke}
		onCancel={() => (toRevoke = null)}
	>
		<p>
			Revoke pending invitation for <strong>{toRevoke.email}</strong>? The token sent
			to them becomes inert immediately.
		</p>
	</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;
	}
	.back {
		font-size: 0.8rem;
		color: var(--color-link);
		text-decoration: none;
	}
	.back:hover {
		text-decoration: underline;
	}
	.subtitle {
		color: var(--text-muted);
		font-size: 0.9rem;
	}
	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;
		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,
	.create-form textarea {
		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,
	.create-form textarea:focus {
		outline: none;
		border-color: var(--color-link);
	}
	.create-form .full-row {
		grid-column: span 2;
	}
	.checkbox-row {
		grid-column: span 2;
		flex-direction: row;
		align-items: center;
		gap: 0.5rem;
	}
	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;
	}
	.muted {
		color: var(--text-muted);
	}
	.error {
		color: var(--color-danger);
		margin: 0.5rem 0;
	}
	button.danger {
		background: var(--color-danger-bg);
		color: var(--color-danger-fg);
		border: 1px solid var(--color-danger-border);
		border-radius: var(--radius-sm);
		padding: 0.2rem 0.5rem;
		font-size: 0.78rem;
		cursor: pointer;
	}
	.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;
	}
</style>
