<script lang="ts">
	import { slide } from 'svelte/transition';
	import { t } from '$lib/i18n';
	import Card from '$lib/components/Card.svelte';
	import IconPicker from '$lib/components/IconPicker.svelte';
	import Hint from '$lib/components/Hint.svelte';
	import EntitySelect from '$lib/components/EntitySelect.svelte';
	import MultiEntitySelect from '$lib/components/MultiEntitySelect.svelte';
	import { getDescriptor } from '$lib/providers';

	interface Props {
		form: {
			name: string;
			icon: string;
			provider_id: number;
			collection_ids: string[];
			scan_interval: number;
			batch_duration: number;
			default_tracking_config_id: number;
			default_template_config_id: number;
			filters: Record<string, any>;
		};
		providerItems: { value: number; label: string; icon: string; desc: string }[];
		collections: any[];
		collectionFilter?: string;
		trackingConfigItems?: { value: number; label: string; icon: string }[];
		templateConfigItems?: { value: number; label: string; icon: string }[];
		editing: number | null;
		submitting: boolean;
		linkCheckLoading: boolean;
		error: string;
		providerType: string;
		onsave: (e: SubmitEvent) => void;
		ontoggleCollection?: (collectionId: string) => void;
		formatDate?: (dateStr: string) => string;
	}

	let {
		form = $bindable(),
		providerItems,
		collections,
		collectionFilter = $bindable(),
		trackingConfigItems = [],
		templateConfigItems = [],
		editing,
		submitting,
		linkCheckLoading,
		error,
		providerType = '',
		onsave,
		ontoggleCollection,
		formatDate,
	}: Props = $props();

	let descriptor = $derived(getDescriptor(providerType));
	let isScheduler = $derived(providerType === 'scheduler');
	let isWebhook = $derived(descriptor?.webhookBased ?? false);
	let colMeta = $derived(descriptor?.collectionMeta);

	// Custom variable management for scheduler
	function addVariable() {
		const vars = { ...(form.filters.custom_variables || {}) };
		const key = `var_${Object.keys(vars).length + 1}`;
		vars[key] = '';
		form.filters = { ...form.filters, custom_variables: vars };
	}
	function removeVariable(key: string) {
		const vars = { ...(form.filters.custom_variables || {}) };
		delete vars[key];
		form.filters = { ...form.filters, custom_variables: vars };
	}
	function updateVariableKey(oldKey: string, newKey: string) {
		if (!newKey || newKey === oldKey) return;
		const vars = { ...(form.filters.custom_variables || {}) };
		const val = vars[oldKey] ?? '';
		delete vars[oldKey];
		vars[newKey] = val;
		form.filters = { ...form.filters, custom_variables: vars };
	}
	function updateVariableValue(key: string, value: string) {
		const vars = { ...(form.filters.custom_variables || {}) };
		vars[key] = value;
		form.filters = { ...form.filters, custom_variables: vars };
	}
</script>

<div in:slide={{ duration: 200 }}>
<Card class="mb-6">
	{#if error}<div class="bg-[var(--color-error-bg)] text-[var(--color-error-fg)] text-sm rounded-md p-3 mb-4">{error}</div>{/if}
	<form onsubmit={onsave} class="space-y-4">
		<div>
			<label for="trk-name" class="block text-sm font-medium mb-1">{t('notificationTracker.name')}</label>
			<div class="flex gap-2">
				<IconPicker value={form.icon} onselect={(v: string) => form.icon = v} />
				<input id="trk-name" bind:value={form.name} required placeholder={t('notificationTracker.namePlaceholder')} class="flex-1 px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
			</div>
		</div>
		<div>
			<label class="block text-sm font-medium mb-1">{t('notificationTracker.server')}</label>
			<EntitySelect items={providerItems} bind:value={form.provider_id} placeholder={t('notificationTracker.selectServer')} />
		</div>
		{#if !isScheduler && colMeta && collections.length > 0}
			<div>
				<label class="block text-sm font-medium mb-1">{t(colMeta.label)}</label>
				<MultiEntitySelect
					items={collections.map(col => ({
						value: col.id,
						label: col.albumName || col.name,
						icon: colMeta.icon,
						desc: colMeta.desc(col),
					}))}
					bind:values={form.collection_ids}
					placeholder={t(colMeta.placeholder)}
				/>
			</div>
		{/if}

		{#if isScheduler}
			<!-- Schedule type -->
			<fieldset class="border border-[var(--color-border)] rounded-md p-3">
				<legend class="text-sm font-medium px-1">{t('notificationTracker.scheduleType')}</legend>
				<div class="flex gap-4 mt-1">
					<label class="flex items-center gap-2 text-sm">
						<input type="radio" name="schedule_type" value="interval"
							checked={!form.filters.schedule_type || form.filters.schedule_type === 'interval'}
							onchange={() => form.filters = { ...form.filters, schedule_type: 'interval' }} />
						{t('notificationTracker.intervalMode')}
					</label>
					<label class="flex items-center gap-2 text-sm">
						<input type="radio" name="schedule_type" value="cron"
							checked={form.filters.schedule_type === 'cron'}
							onchange={() => form.filters = { ...form.filters, schedule_type: 'cron' }} />
						{t('notificationTracker.cronMode')}
					</label>
				</div>
				{#if form.filters.schedule_type === 'cron'}
					<div class="mt-3">
						<label for="trk-cron" class="block text-xs mb-1">{t('notificationTracker.cronExpression')}</label>
						<input id="trk-cron" value={form.filters.cron_expression || ''}
							oninput={(e) => form.filters = { ...form.filters, cron_expression: (e.target as HTMLInputElement).value }}
							placeholder="0 9 * * 1-5" class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)] font-mono" />
						<p class="text-xs text-[var(--color-muted-foreground)] mt-1">{t('notificationTracker.cronHint')}</p>
					</div>
				{:else}
					<div class="mt-3">
						<label for="trk-interval" class="block text-xs mb-1">{t('notificationTracker.scanInterval')}<Hint text={t('hints.scanInterval')} /></label>
						<input id="trk-interval" type="number" bind:value={form.scan_interval} min="60" max="86400" class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
					</div>
				{/if}
			</fieldset>

			<!-- Custom variables -->
			<fieldset class="border border-[var(--color-border)] rounded-md p-3">
				<legend class="text-sm font-medium px-1">{t('notificationTracker.customVariables')}</legend>
				<p class="text-xs text-[var(--color-muted-foreground)] mb-2">{t('notificationTracker.customVariablesHint')}</p>
				{#each Object.entries(form.filters.custom_variables || {}) as [key, value]}
					<div class="flex gap-2 mb-2 items-center">
						<input value={key} onblur={(e) => updateVariableKey(key, (e.target as HTMLInputElement).value)}
							placeholder="key" class="w-1/3 px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)] font-mono" />
						<input value={value} oninput={(e) => updateVariableValue(key, (e.target as HTMLInputElement).value)}
							placeholder="value" class="flex-1 px-2 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
						<button type="button" onclick={() => removeVariable(key)}
							class="text-[var(--color-error-fg)] hover:opacity-70 text-sm px-1">✕</button>
					</div>
				{/each}
				<button type="button" onclick={addVariable}
					class="text-xs text-[var(--color-primary)] hover:underline mt-1">+ {t('notificationTracker.addVariable')}</button>
			</fieldset>
		{:else}
		<div class="grid grid-cols-2 gap-3">
			{#if !isWebhook}
			<div>
				<label for="trk-interval" class="block text-sm font-medium mb-1">{t('notificationTracker.scanInterval')}<Hint text={t('hints.scanInterval')} /></label>
				<input id="trk-interval" type="number" bind:value={form.scan_interval} min="10" max="3600" class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
			</div>
			{/if}
			<div>
				<label for="trk-batch" class="block text-sm font-medium mb-1">{t('notificationTracker.batchDuration')}<Hint text={t('hints.batchDuration')} /></label>
				<input id="trk-batch" type="number" bind:value={form.batch_duration} min="0" max="3600" class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
			</div>
		</div>
		{/if}

		<!-- Default configs -->
		{#if trackingConfigItems.length > 0 || templateConfigItems.length > 0}
		<div class="grid grid-cols-2 gap-3">
			{#if trackingConfigItems.length > 0}
			<div>
				<label class="block text-sm font-medium mb-1">{t('notificationTracker.defaultTrackingConfig')}<Hint text={t('hints.defaultTrackingConfig')} /></label>
				<EntitySelect items={[{value: 0, label: t('common.none'), icon: 'mdiMinus'}, ...trackingConfigItems]} bind:value={form.default_tracking_config_id} placeholder={t('common.none')} />
			</div>
			{/if}
			{#if templateConfigItems.length > 0}
			<div>
				<label class="block text-sm font-medium mb-1">{t('notificationTracker.defaultTemplateConfig')}<Hint text={t('hints.defaultTemplateConfig')} /></label>
				<EntitySelect items={[{value: 0, label: t('common.none'), icon: 'mdiMinus'}, ...templateConfigItems]} bind:value={form.default_template_config_id} placeholder={t('common.none')} />
			</div>
			{/if}
		</div>
		{/if}

		<button type="submit" disabled={submitting || linkCheckLoading} class="px-4 py-2 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50">
			{#if linkCheckLoading}{t('notificationTracker.checkingLinks')}{:else}{editing ? t('common.save') : t('notificationTracker.createTracker')}{/if}
		</button>
	</form>
</Card>
</div>
