<script lang="ts">
	import type { IntegrationFieldDescriptor } from '$lib/server/integrations/types.js';
	import Switch from '$lib/components/ui/Switch.svelte';

	interface Props {
		fields: IntegrationFieldDescriptor[];
		values: Record<string, unknown>;
		onchange: (name: string, value: unknown) => void;
		idPrefix?: string;
	}

	let { fields, values, onchange, idPrefix = 'int' }: Props = $props();

	const inputClass = 'w-full rounded-xl border border-input bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground transition-colors focus:border-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/30';
</script>

<div class="space-y-3">
	{#each fields as field (field.name)}
		<div>
			<label for="{idPrefix}-{field.name}" class="mb-1 block text-sm font-medium text-card-foreground">
				{field.label}
				{#if field.required}
					<span class="text-destructive">*</span>
				{/if}
			</label>
			{#if field.type === 'boolean'}
				<div class="flex items-center gap-3">
					<Switch
						id="{idPrefix}-{field.name}"
						checked={!!values[field.name]}
						onchange={(checked) => onchange(field.name, checked)}
						ariaLabel={field.label}
					/>
					<span class="text-sm text-muted-foreground">{field.description ?? ''}</span>
				</div>
			{:else if field.type === 'number'}
				<input
					id="{idPrefix}-{field.name}"
					type="number"
					value={values[field.name] ?? ''}
					oninput={(e) => onchange(field.name, parseInt(e.currentTarget.value) || 0)}
					class={inputClass}
					placeholder={field.description ?? ''}
				/>
			{:else}
				<input
					id="{idPrefix}-{field.name}"
					type={field.name.toLowerCase().includes('password') || field.name.toLowerCase().includes('secret') ? 'password' : 'text'}
					value={values[field.name] ?? ''}
					oninput={(e) => onchange(field.name, e.currentTarget.value)}
					class={inputClass}
					placeholder={field.description ?? field.label}
				/>
			{/if}
		</div>
	{/each}
</div>
