<script lang="ts">
	import { Checkbox, Label } from 'bits-ui';
	import type { AgentRoleRow, AgentModelRow, AgentSkillRow } from '$lib/api';
	import { api } from '$lib/api';
	import { fmtDate } from '$lib/format';
	import { TOOL_OPTIONS } from '$lib/constants';
	import SelectField from '$lib/components/SelectField.svelte';
	import CheckboxControl from '$lib/components/CheckboxControl.svelte';
	import Icon from '$lib/components/Icon.svelte';
	import { toastError, toastSuccess } from '$lib/toast';

	let {
		r,
		models,
		skills,
		slug,
		onupdated,
		onskillschanged,
	}: {
		r: AgentRoleRow;
		models: AgentModelRow[];
		skills: AgentSkillRow[];
		slug: string;
		onupdated: (updated: AgentRoleRow) => void;
		onskillschanged: (roleId: string, skillNames: string[]) => void;
	} = $props();

	const initial = {
		label: r.label,
		defaultModel: r.defaultModel ?? '',
		systemPrompt: r.systemPrompt ?? '',
		unrestricted: r.tools === null,
		tools: r.tools ?? [],
		sortOrder: String(r.sortOrder),
		isDefault: r.isDefault,
		skillNames: r.skillNames,
	};
	let label = $state(initial.label);
	let defaultModel = $state(initial.defaultModel);
	let systemPrompt = $state(initial.systemPrompt);
	let unrestricted = $state(initial.unrestricted);
	let selectedTools = $state<string[]>([...initial.tools]);
	let sortOrder = $state(initial.sortOrder);
	let isDefault = $state(initial.isDefault);
	let selectedSkills = $state<string[]>([...initial.skillNames]);
	let saving = $state(false);

	const groupedTools = TOOL_OPTIONS.reduce(
		(acc, t) => {
			(acc[t.group] ??= []).push(t);
			return acc;
		},
		{} as Record<string, typeof TOOL_OPTIONS>,
	);

	const modelItems = $derived([
		{ value: '', label: '（使用平台默认模型）' },
		...models.map((m) => ({ value: m.id, label: `${m.label}（${m.id}）` })),
	]);

	const skillItems = $derived(skills.map((s) => ({ value: s.name, label: s.name })));

	function skillsDirty(): boolean {
		const a = [...selectedSkills].sort();
		const b = [...r.skillNames].sort();
		return a.length !== b.length || a.some((v, i) => v !== b[i]);
	}

	async function save() {
		const trimmedLabel = label.trim();
		if (trimmedLabel === '') {
			toastError('显示名不能为空');
			return;
		}
		const order = Number(sortOrder);
		if (sortKeyDirty() && (!Number.isSafeInteger(order) || order < 0)) {
			toastError('排序必须为非负整数');
			return;
		}
		saving = true;
		const tools = unrestricted ? null : selectedTools;
		try {
			const updated = await api.upsertAgentRole(slug, r.roleId, {
				label: trimmedLabel,
				defaultModel: defaultModel === '' ? null : defaultModel,
				systemPrompt: systemPrompt === '' ? null : systemPrompt,
				tools,
				...(sortKeyDirty() ? { sortOrder: order } : {}),
				isDefault,
			});
			onupdated(updated);
			if (skillsDirty()) {
				const res = await api.setAgentRoleSkills(slug, r.roleId, selectedSkills);
				selectedSkills = [...res.skillNames];
				onskillschanged(r.roleId, res.skillNames);
			}
			toastSuccess('角色已保存');
		} catch (err) {
			toastError(err instanceof Error ? err.message : String(err));
		} finally {
			saving = false;
		}
	}

	function sortKeyDirty(): boolean {
		return Number(sortOrder) !== r.sortOrder;
	}
</script>

<div class="saas-card-pad">
	<div class="mb-4 flex flex-wrap items-center gap-2">
		<span class="saas-badge-primary font-mono">/{r.roleId}</span>
		<span class="text-sm text-surface-700">{label || r.label}</span>
		{#if r.isDefault}
			<span class="saas-badge-success">默认</span>
		{/if}
	</div>

	<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
		<div>
			<Label.Root for="role-label-{r.id}" class="saas-label">显示名</Label.Root>
			<input id="role-label-{r.id}" class="saas-input" bind:value={label} />
		</div>
		<div>
			<Label.Root for="role-sort-{r.id}" class="saas-label">排序</Label.Root>
			<input id="role-sort-{r.id}" class="saas-input" type="number" min="0" bind:value={sortOrder} />
		</div>
	</div>

	<div class="mt-4">
		<p class="saas-label">默认模型</p>
		<SelectField items={modelItems} bind:value={defaultModel} />
	</div>

	<div class="mt-4">
		<span class="saas-label">工具白名单</span>
		<label class="mb-3 flex cursor-pointer items-center gap-2 border border-surface-300 bg-surface-100 px-3 py-2">
			<CheckboxControl bind:checked={unrestricted} />
			<span class="text-sm">不限（使用全部注册工具）</span>
		</label>
		<div class="space-y-3 {unrestricted ? 'pointer-events-none opacity-40' : ''}">
			<Checkbox.Group bind:value={selectedTools} disabled={unrestricted}>
				{#each Object.entries(groupedTools) as [group, tools]}
					<div>
						<p class="mb-1.5 text-xs font-semibold uppercase tracking-wide text-surface-600">{group}</p>
						<div class="grid grid-cols-1 gap-1.5 sm:grid-cols-2">
							{#each tools as t}
								<label class="flex cursor-pointer items-center gap-2 px-2 py-1.5 text-sm hover:bg-surface-100">
									<Checkbox.Root class="saas-checkbox" value={t.id} id={`tool-${r.id}-${t.id}`}>
										{#snippet children({ checked })}
											{#if checked}
												<Icon name="check" class="h-3.5 w-3.5" />
											{/if}
										{/snippet}
									</Checkbox.Root>
									<span>{t.label}</span>
								</label>
							{/each}
						</div>
					</div>
				{/each}
			</Checkbox.Group>
		</div>
	</div>

	<div class="mt-4">
		<span class="saas-label">技能绑定</span>
		{#if skills.length === 0}
			<p class="text-sm text-surface-600">组织内暂无已安装技能。技能通过 CLI / seed 安装（ADR-0018）。</p>
		{:else}
			<div class="grid grid-cols-1 gap-1.5 sm:grid-cols-2">
				{#each skillItems as s}
					<label class="flex cursor-pointer items-center gap-2 px-2 py-1.5 text-sm hover:bg-surface-100">
						<CheckboxControl
							checked={selectedSkills.includes(s.value)}
							onchange={(checked) => {
								selectedSkills = checked ? [...selectedSkills, s.value] : selectedSkills.filter((x) => x !== s.value);
							}}
						/>
						<span class="font-mono text-xs">{s.label}</span>
					</label>
				{/each}
			</div>
		{/if}
	</div>

	<div class="mt-4">
		<Label.Root for="role-prompt-{r.id}" class="saas-label">系统提示词</Label.Root>
		<textarea
			id="role-prompt-{r.id}"
			class="saas-textarea"
			rows="4"
			placeholder="系统提示词（可选）。会话开始时注入，定义智能体人格/指令。"
			bind:value={systemPrompt}></textarea>
	</div>

	<div class="mt-4 flex flex-wrap items-center gap-3 border-t border-surface-100 pt-4">
		<label class="flex cursor-pointer items-center gap-2">
			<CheckboxControl bind:checked={isDefault} />
			<span class="text-sm">设为组织默认角色</span>
		</label>
		<span class="text-xs text-surface-600">更新于 {fmtDate(r.updatedAt)}</span>
		<div class="flex-1"></div>
		<button class="saas-btn-primary" onclick={save} disabled={saving}>
			{saving ? '保存中…' : '保存'}
		</button>
	</div>
</div>
