<script lang="ts">
	import { Card, Button, Badge, DataTable, Spinner } from '$lib/components';
	import { deleteTenant } from '$lib/api/admin';
	import { toast } from '$lib/stores/toast.svelte';
	import { data } from '$lib/stores/data.svelte';
	import type { Tenant } from '$lib/types';
	import { Plus, Pencil, Trash2, Users, Eye } from 'lucide-svelte';
	import { goto } from '$app/navigation';
	import TenantModal from './TenantModal.svelte';
	import { navbarExtra } from '$lib/stores/navbar-extra.svelte';
	import { onDestroy } from 'svelte';

	let modalOpen = $state(false);
	let editingTenant = $state<Tenant | null>(null);
	let deleteConfirmId = $state<string | null>(null);
	let deleting = $state(false);

	const statusColor: Record<string, 'emerald' | 'amber' | 'rose'> = {
		active: 'emerald',
		suspended: 'amber',
		archived: 'rose'
	};

	function openCreate() {
		editingTenant = null;
		modalOpen = true;
	}

	$effect(() => {
		navbarExtra.set(addTenantBtn);
		return () => navbarExtra.set(null);
	});
	onDestroy(() => navbarExtra.set(null));

	function openEdit(tenant: Tenant) {
		editingTenant = tenant;
		modalOpen = true;
	}

	async function handleDelete(id: string) {
		deleting = true;
		try {
			await deleteTenant(id);
			await data.refetchTenants();
			toast.success(`Tenant ${id} deleted`);
			deleteConfirmId = null;
		} catch (err: any) {
			toast.error(err.message ?? 'Failed to delete tenant');
		} finally {
			deleting = false;
		}
	}

	function formatDuration(ms: number): string {
		if (ms < 60000) return `${Math.round(ms / 1000)}s`;
		return `${Math.round(ms / 60000)}m`;
	}

	function formatMemory(mb: number): string {
		if (mb >= 1024) return `${(mb / 1024).toFixed(1)}G`;
		return `${mb}M`;
	}

	const globalProvider = $derived.by(() => data.settings?.default_provider ?? 'codex');
	function effectiveProvider(t: Tenant): 'claude' | 'codex' {
		return (t.provider ?? globalProvider) as any;
	}
	function providerLabel(t: Tenant): string {
		return t.provider ? t.provider : `default (${effectiveProvider(t)})`;
	}
</script>

{#snippet addTenantBtn()}
	<Button variant="primary" onclick={openCreate}>
		<Plus size={16} />
		<span class="btn-label">Add Tenant</span>
	</Button>
{/snippet}

{#snippet mobileRow(tenant: Tenant)}
	<a href="/tenants/{tenant.id}" class="tenant-card">
		<div class="tc-header">
			<span class="tc-id mono">{tenant.id}</span>
			<Badge color={statusColor[tenant.status] ?? 'dim'}>{tenant.status}</Badge>
		</div>
			<div class="tc-body">
				<span class="tc-name">{tenant.name}</span>
				<div class="tc-meta">
					<Badge color={effectiveProvider(tenant) === 'codex' ? 'accent' : 'cyan'}>{providerLabel(tenant)}</Badge>
				{#if tenant.tenant_type === 'bot'}<Badge color="accent">bot</Badge>{/if}
				<span class="tc-groups"><Users size={12} />{tenant.groups?.length ?? 0}</span>
				</div>
			</div>
	</a>
{/snippet}

<div class="page">
	{#if !data.initialLoaded}
		<div class="center"><Spinner size={28} /></div>
	{:else}
		<Card>
			<DataTable data={data.tenants} empty="No tenants configured" {mobileRow}>
				{#snippet header()}
					<th>ID</th>
					<th>Name</th>
					<th>Status</th>
					<th>Type</th>
					<th>Provider</th>
					<th>Model</th>
					<th>Groups</th>
					<th>Daily Runs</th>
					<th>Memory</th>
					<th>CPU</th>
					<th>Disk</th>
					<th>Actions</th>
				{/snippet}

				{#snippet children(tenant)}
					<td class="id-cell">
						<a class="row-link" href="/tenants/{tenant.id}">{tenant.id}</a>
					</td>
					<td>{tenant.name}</td>
					<td><Badge color={statusColor[tenant.status] ?? 'dim'}>{tenant.status}</Badge></td>
					<td>
						{#if tenant.tenant_type === 'bot'}
							<Badge color="accent">bot</Badge>
						{:else}
							<span class="dim">standard</span>
						{/if}
					</td>
					<td><Badge color={effectiveProvider(tenant) === 'codex' ? 'accent' : 'cyan'}>{providerLabel(tenant)}</Badge></td>
					<td>
						{#if tenant.model}
							<span class="mono">{tenant.model}</span>
						{:else}
							<span class="dim">default</span>
						{/if}
					</td>
					<td>
						<span class="groups-count"><Users size={13} />{tenant.groups?.length ?? 0}</span>
					</td>
					<td>
						{#if tenant.daily_usage}
							<span class="mono">
								{tenant.daily_usage.requests}{#if tenant.daily_usage.limit_requests}<span class="dim">/{tenant.daily_usage.limit_requests}</span>{/if}
							</span>
							{#if tenant.daily_usage.duration_ms > 0}
								<span class="duration-sub">{formatDuration(tenant.daily_usage.duration_ms)}{#if tenant.daily_usage.limit_duration_ms}<span class="dim">/{formatDuration(tenant.daily_usage.limit_duration_ms)}</span>{/if}</span>
							{/if}
						{:else}
							<span class="dim">--</span>
						{/if}
					</td>
					<td><span class="mono">{formatMemory(tenant.max_memory_mb)}</span></td>
					<td><span class="mono">{tenant.cpu_quota}</span></td>
					<td><span class="mono">{formatMemory(tenant.max_disk_mb)}</span></td>
					<td>
						<div class="actions">
							<Button variant="ghost" size="sm" onclick={() => goto(`/tenants/${tenant.id}`)} title="View"><Eye size={14} /></Button>
							<Button variant="ghost" size="sm" onclick={() => openEdit(tenant)} title="Edit"><Pencil size={14} /></Button>
							{#if deleteConfirmId === tenant.id}
								<Button variant="danger" size="sm" loading={deleting} onclick={() => handleDelete(tenant.id)}>Confirm</Button>
								<Button variant="ghost" size="sm" onclick={() => (deleteConfirmId = null)}>Cancel</Button>
							{:else}
								<Button variant="ghost" size="sm" onclick={() => (deleteConfirmId = tenant.id)} title="Delete"><Trash2 size={14} /></Button>
							{/if}
						</div>
					</td>
				{/snippet}
			</DataTable>
		</Card>
	{/if}
</div>

<TenantModal
	open={modalOpen}
	tenant={editingTenant}
	credentials={data.credentials}
	onclose={() => (modalOpen = false)}
	onsave={async () => { await data.refetchTenants(); }}
/>

<style>
	.page { display: flex; flex-direction: column; gap: 20px; }
	.center { display: flex; justify-content: center; padding: 48px; }
	.id-cell { font-family: var(--font-mono); font-weight: 500; }
	.row-link {
		background: none; border: none; color: var(--accent);
		cursor: pointer; font: inherit; padding: 0; text-decoration: none;
	}
	.row-link:hover { text-decoration: underline; }
	.dim { color: var(--text-muted); }
	.mono { font-family: var(--font-mono); font-size: var(--font-size-sm); }
	.groups-count {
		display: inline-flex; align-items: center; gap: 4px;
		color: var(--text-dim); font-family: var(--font-mono); font-size: var(--font-size-sm);
	}
	.duration-sub {
		display: block; font-family: var(--font-mono);
		font-size: var(--font-size-xs); color: var(--text-dim);
	}
	.actions { display: flex; gap: 4px; align-items: center; }
	/* Mobile tenant cards */
	.tenant-card {
		display: flex;
		flex-direction: column;
		gap: 6px;
		padding: 14px 16px;
		border-bottom: 1px solid var(--border-subtle);
		text-decoration: none;
		color: inherit;
		transition: background var(--duration) var(--ease);
	}
	.tenant-card:hover { background: var(--surface-hover); }
	.tc-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	.tc-id {
		font-family: var(--font-mono);
		font-size: var(--font-size-sm);
		color: var(--accent);
		font-weight: 500;
	}
	.tc-body { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
	.tc-name { font-size: var(--font-size-sm); color: var(--text); font-weight: 500; }
	.tc-meta { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
	.tc-groups {
		display: inline-flex; align-items: center; gap: 3px;
		font-size: var(--font-size-xs); color: var(--text-dim); font-family: var(--font-mono);
	}
	@media (max-width: 768px) {
		.btn-label { display: none; }
	}
</style>
