<script lang="ts">
	import { Building2, Plus, ShieldAlert, RefreshCw } 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);

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

	// Valores repoblados tras un fallo de validación del servidor.
	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 : '';
	}
</script>

<div class="space-y-6">
	<div>
		<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight">
			<Building2 class="h-6 w-6" /> Organizaciones del workspace
		</h1>
		<p class="mt-1 text-sm text-muted-foreground">
			Da de alta un cliente nuevo (tenant). Se crea su realm en Keycloak y su licencia base.
		</p>
	</div>

	{#if data.forbidden}
		<Card.Root>
			<Card.Content class="flex items-start gap-3 pt-6">
				<ShieldAlert class="mt-0.5 h-5 w-5 text-amber-500" />
				<div class="text-sm">
					<p class="font-medium">Requiere permisos de administrador del workspace</p>
					<p class="mt-1 text-muted-foreground">
						El alta de organizaciones solo está disponible para administradores del Hub
						(<code>hub_admin</code>). Tu usuario actual no tiene ese rol.
					</p>
				</div>
			</Card.Content>
		</Card.Root>
	{:else}
		{#if data.loadError}
			<div class="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
				No se pudo consultar el workspace: {data.loadError}
			</div>
		{/if}

		<!-- Alta de organización -->
		<Card.Root>
			<Card.Header>
				<Card.Title class="flex items-center gap-2"><Plus class="h-4 w-4" /> Nueva organización</Card.Title>
				<Card.Description>El slug identifica al tenant; no se puede cambiar después.</Card.Description>
			</Card.Header>
			<Card.Content>
				<form
					method="POST"
					action="?/create"
					use:enhance={() => {
						submitting = true;
						return async ({ result, update }) => {
							submitting = false;
							if (result.type === 'success') {
								toast.success(`Organización creada: ${result.data?.tenantName ?? ''}`);
								await update({ reset: true });
							} else if (result.type === 'failure') {
								toast.error(String(result.data?.error ?? 'No se pudo crear la organizació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">Nombre / Razón social *</span>
							<input class={inputCls} name="name" required minlength="2" value={prev('name')} />
						</label>
						<label class="flex flex-col gap-1 text-sm">
							<span class="font-medium">Slug *</span>
							<input
								class="font-mono {inputCls}"
								name="slug"
								required
								pattern="[a-z0-9-]+"
								placeholder="empresa-abc"
								title="Solo minúsculas, dígitos y guiones"
								value={prev('slug')}
							/>
						</label>
						<label class="flex flex-col gap-1 text-sm">
							<span class="font-medium">Nombre para mostrar</span>
							<input class={inputCls} name="display_name" value={prev('display_name')} />
						</label>
						<label class="flex flex-col gap-1 text-sm">
							<span class="font-medium">Contacto (nombre)</span>
							<input class={inputCls} name="contact_name" value={prev('contact_name')} />
						</label>
						<label class="flex flex-col gap-1 text-sm">
							<span class="font-medium">Email de contacto *</span>
							<input type="email" class={inputCls} name="contact_email" required value={prev('contact_email')} />
						</label>
						<label class="flex flex-col gap-1 text-sm">
							<span class="font-medium">Teléfono de contacto</span>
							<input class={inputCls} name="contact_phone" value={prev('contact_phone')} />
						</label>
						<label class="flex flex-col gap-1 text-sm">
							<span class="font-medium">URL de la app (opcional)</span>
							<input class={inputCls} name="app_url" placeholder="https://app.empresa-abc.com" value={prev('app_url')} />
						</label>
						<label class="flex items-center gap-2 text-sm sm:col-span-2">
							<input type="checkbox" name="is_self_hosted" class="h-4 w-4 rounded border" />
							<span>Cliente self-hosted (instalación propia)</span>
						</label>
					</div>

					<div class="mt-6 flex justify-end border-t pt-4">
						<Button type="submit" disabled={submitting}>
							{submitting ? 'Creando…' : 'Crear organización'}
						</Button>
					</div>
				</form>
			</Card.Content>
		</Card.Root>

		<!-- Organizaciones existentes -->
		<Card.Root>
			<Card.Header>
				<Card.Title>Organizaciones ({data.tenants.length})</Card.Title>
				<Card.Description>Tenants activos en el workspace.</Card.Description>
			</Card.Header>
			<Card.Content>
				{#if data.tenants.length === 0}
					<p class="flex items-center gap-2 text-sm text-muted-foreground">
						<RefreshCw class="h-4 w-4" /> Aún no hay organizaciones registradas.
					</p>
				{:else}
					<div class="overflow-x-auto">
						<table class="w-full text-sm">
							<thead class="text-left text-muted-foreground">
								<tr class="border-b">
									<th class="py-2 pr-4 font-medium">Nombre</th>
									<th class="py-2 pr-4 font-medium">Slug</th>
									<th class="py-2 pr-4 font-medium">Contacto</th>
									<th class="py-2 pr-4 font-medium">Estatus</th>
									<th class="py-2 pr-4 font-medium">Licencia</th>
								</tr>
							</thead>
							<tbody>
								{#each data.tenants as t (t.id)}
									<tr class="border-b last:border-0">
										<td class="py-2 pr-4">{t.display_name || t.name}</td>
										<td class="py-2 pr-4 font-mono text-xs">{t.slug}</td>
										<td class="py-2 pr-4">{t.contact_email}</td>
										<td class="py-2 pr-4">
											<span
												class="rounded-full px-2 py-0.5 text-xs {t.status === 'active'
													? 'bg-emerald-500/15 text-emerald-600'
													: 'bg-muted text-muted-foreground'}"
											>
												{t.status}
											</span>
										</td>
										<td class="py-2 pr-4">{t.has_license ? 'Sí' : '—'}</td>
									</tr>
								{/each}
							</tbody>
						</table>
					</div>
				{/if}
			</Card.Content>
		</Card.Root>
	{/if}
</div>
