<script lang="ts">
	import { UserPlus, Copy, Check, MailCheck } from '@lucide/svelte';
	import { enhance } from '$app/forms';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { toast } from 'svelte-sonner';
	import type { PageData, ActionData } from './$types';

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

	let submitting = $state(false);
	let copied = $state(false);

	const inputCls =
		'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';

	const v = $derived((form && 'values' in form ? form.values : null) as Record<string, unknown> | null);
	function prev(field: string): string {
		const val = v?.[field];
		return typeof val === 'string' ? val : '';
	}

	// Invitación recién creada (para copiar/compartir el enlace).
	const created = $derived(
		form && 'success' in form && form.success
			? { email: form.email, inviteUrl: form.inviteUrl }
			: null
	);

	async function copyInvite(url: string) {
		try {
			await navigator.clipboard.writeText(url);
			copied = true;
			toast.success('Enlace de invitación copiado');
			setTimeout(() => (copied = false), 2000);
		} catch {
			toast.error('No se pudo copiar el enlace');
		}
	}
</script>

<div class="space-y-6">
	<div>
		<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
			<UserPlus class="h-6 w-6" /> Alta de usuarios (invitaciones)
		</h1>
		<p class="mt-1 text-sm text-muted-foreground">
			Invita a un usuario a una organización del workspace. Recibe un enlace de un solo uso para
			fijar su contraseña y activarse.
		</p>
	</div>

	{#if created}
		<Card.Root class="border-emerald-500/40">
			<Card.Content class="pt-6">
				<div class="flex items-start gap-3">
					<MailCheck class="mt-0.5 h-5 w-5 text-emerald-600" />
					<div class="min-w-0 flex-1 text-sm">
						<p class="font-medium">Invitación enviada a {created.email}</p>
						<p class="mt-1 text-muted-foreground">
							Si el correo no llega, comparte este enlace directamente:
						</p>
						<div class="mt-2 flex items-center gap-2">
							<input class="flex-1 font-mono text-xs {inputCls}" readonly value={created.inviteUrl} />
							<Button variant="outline" size="sm" onclick={() => copyInvite(String(created.inviteUrl))}>
								{#if copied}<Check class="h-4 w-4" />{:else}<Copy class="h-4 w-4" />{/if}
							</Button>
						</div>
					</div>
				</div>
			</Card.Content>
		</Card.Root>
	{/if}

	<Card.Root>
		<Card.Header>
			<Card.Title>Nueva invitación</Card.Title>
			<Card.Description>Elige la compañía destino y el rol del usuario.</Card.Description>
		</Card.Header>
		<Card.Content>
			<form
				method="POST"
				action="?/invite"
				use:enhance={() => {
					submitting = true;
					return async ({ result, update }) => {
						submitting = false;
						if (result.type === 'success') {
							toast.success('Invitación creada');
							await update({ reset: true });
						} else if (result.type === 'failure') {
							toast.error(String(result.data?.error ?? 'No se pudo crear la invitación'));
							await update({ reset: false });
						} else {
							await update();
						}
					};
				}}
			>
				<div class="grid gap-4 sm:grid-cols-2">
					<label class="flex flex-col gap-1 text-sm sm:col-span-2">
						<span class="font-medium">Email del usuario *</span>
						<input type="email" class={inputCls} name="email" required value={prev('email')} />
					</label>

					<label class="flex flex-col gap-1 text-sm">
						<span class="font-medium">Compañía destino *</span>
						{#if data.companies.length > 0}
							<select class={inputCls} name="tenant_slug" required value={prev('tenant_slug')}>
								<option value="" disabled>Selecciona…</option>
								{#each data.companies as c (c.id)}
									<option value={c.tenant_slug}>{c.name} — {c.tenant_name}</option>
								{/each}
							</select>
						{:else}
							<span class="rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground">
								No hay compañías disponibles en tu tenant. Crea una en Compañías.
							</span>
							<input type="hidden" name="tenant_slug" value="" />
						{/if}
					</label>

					<label class="flex flex-col gap-1 text-sm">
						<span class="font-medium">Rol *</span>
						<select class={inputCls} name="role" required value={prev('role') || 'user'}>
							{#each data.roles as r (r)}
								<option value={r}>{r}</option>
							{/each}
						</select>
					</label>
				</div>

				<div class="mt-6 flex justify-end border-t pt-4">
					<Button type="submit" disabled={submitting || data.companies.length === 0}>
						{submitting ? 'Enviando…' : 'Enviar invitación'}
					</Button>
				</div>
			</form>
		</Card.Content>
	</Card.Root>
</div>
