<script lang="ts">
	import { api } from '$lib/api';
	import { t } from '$lib/i18n';
	import { providersCache } from '$lib/stores/caches.svelte';
	import { snackSuccess, snackError } from '$lib/stores/snackbar.svelte';
	import MdiIcon from '$lib/components/MdiIcon.svelte';
	import IconButton from '$lib/components/IconButton.svelte';
	import EntitySelect from '$lib/components/EntitySelect.svelte';
	import MultiEntitySelect from '$lib/components/MultiEntitySelect.svelte';
	import type { ActionRule } from '$lib/types';

	let { actionId, actionType, providerId }: { actionId: number; actionType: string; providerId: number } = $props();

	let rules = $state<ActionRule[]>([]);
	let loading = $state(true);
	let expandedRule = $state<number | null>(null);
	let showAddForm = $state(false);
	let submitting = $state(false);

	// People and albums from Immich provider
	let people = $state<{ id: string; name: string }[]>([]);
	let albums = $state<{ id: string; name: string }[]>([]);

	// EntitySelect items
	let personItems = $derived(people.map(p => ({ value: p.id, label: p.name, icon: 'mdiAccount' })));
	let albumItems = $derived(albums.map(a => ({ value: a.id, label: a.name, icon: 'mdiImageMultiple' })));

	// Temp value for person picker (add-one-at-a-time flow)
	let personPickerValue = $state<string | null>(null);

	let newRule = $state({
		name: '',
		rule_config: {
			criteria: { person_ids: [] as string[], person_names: [] as string[], query: '', asset_type: 'all', date_from: '', date_to: '', favorite_only: false },
			target_album_ids: [] as string[], target_album_names: [] as string[],
			target_album_id: '', target_album_name: '',
			create_album_if_missing: false, create_album_name: '',
		},
	});

	$effect(() => {
		loadRules();
		loadProviderData();
	});

	async function loadRules() {
		loading = true;
		try {
			rules = await api<ActionRule[]>(`/actions/${actionId}/rules`);
		} catch (err: any) { snackError(err.message); }
		loading = false;
	}

	async function loadProviderData() {
		if (actionType !== 'auto_organize') return;
		const provider = providersCache.items.find((p: any) => p.id === providerId);
		if (!provider || provider.type !== 'immich') return;
		try {
			const [p, a] = await Promise.all([
				api<any>(`/providers/${providerId}/people`),
				api<any>(`/providers/${providerId}/collections`),
			]);
			people = Array.isArray(p) ? p : [];
			albums = Array.isArray(a) ? a : [];
		} catch {
			// People/album endpoints may not exist yet — degrade gracefully
		}
	}

	async function addRule() {
		submitting = true;
		try {
			const maxOrder = rules.reduce((max, r) => Math.max(max, r.order), -1);
			await api(`/actions/${actionId}/rules`, {
				method: 'POST',
				body: JSON.stringify({ name: newRule.name, rule_config: newRule.rule_config, order: maxOrder + 1 }),
			});
			showAddForm = false;
			resetNewRule();
			await loadRules();
			snackSuccess(t('actions.ruleSaved'));
		} catch (err: any) { snackError(err.message); }
		submitting = false;
	}

	async function updateRule(rule: ActionRule) {
		try {
			await api(`/actions/${actionId}/rules/${rule.id}`, {
				method: 'PUT',
				body: JSON.stringify({ name: rule.name, rule_config: rule.rule_config, enabled: rule.enabled }),
			});
			await loadRules();
			snackSuccess(t('actions.ruleSaved'));
		} catch (err: any) { snackError(err.message); }
	}

	async function deleteRule(ruleId: number) {
		try {
			await api(`/actions/${actionId}/rules/${ruleId}`, { method: 'DELETE' });
			await loadRules();
			snackSuccess(t('actions.ruleDeleted'));
		} catch (err: any) { snackError(err.message); }
	}

	async function toggleRule(rule: ActionRule) {
		rule.enabled = !rule.enabled;
		await updateRule(rule);
	}

	function resetNewRule() {
		newRule = {
			name: '',
			rule_config: {
				criteria: { person_ids: [], person_names: [], query: '', asset_type: 'all', date_from: '', date_to: '', favorite_only: false },
				target_album_ids: [] as string[], target_album_names: [] as string[],
				target_album_id: '', target_album_name: '',
				create_album_if_missing: false, create_album_name: '',
			},
		};
	}

	function selectPerson(ruleConfig: any, personId: string, personName: string) {
		const ids = ruleConfig.criteria.person_ids || [];
		const names = ruleConfig.criteria.person_names || [];
		if (ids.includes(personId)) {
			ruleConfig.criteria.person_ids = ids.filter((id: string) => id !== personId);
			ruleConfig.criteria.person_names = names.filter((n: string) => n !== personName);
		} else {
			ruleConfig.criteria.person_ids = [...ids, personId];
			ruleConfig.criteria.person_names = [...names, personName];
		}
	}

	function selectAlbum(ruleConfig: any, albumId: string, albumName: string) {
		ruleConfig.target_album_id = albumId;
		ruleConfig.target_album_name = albumName;
	}
</script>

<div class="space-y-3">
	<div class="flex items-center justify-between">
		<h3 class="text-sm font-semibold">{t('actions.rules')} ({rules.length})</h3>
		<button onclick={() => { showAddForm = !showAddForm; if (showAddForm) resetNewRule(); }}
			class="text-xs px-2 py-1 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded hover:opacity-90">
			{showAddForm ? t('common.cancel') : t('actions.addRule')}
		</button>
	</div>

	{#if loading}
		<p class="text-sm text-[var(--color-muted-foreground)]">{t('common.loading')}...</p>
	{/if}

	{#if showAddForm}
		<div class="border border-[var(--color-border)] rounded-md p-3 space-y-2 bg-[var(--color-muted)]/30">
			<div>
				<label class="block text-xs font-medium mb-1">{t('actions.ruleName')}</label>
				<input bind:value={newRule.name} placeholder={t('actions.ruleNamePlaceholder')}
					class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
			</div>

			{#if actionType === 'auto_organize'}
				{@render criteriaFields(newRule.rule_config)}
			{/if}

			<button onclick={addRule} disabled={submitting}
				class="text-xs px-3 py-1.5 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded hover:opacity-90 disabled:opacity-50">
				{submitting ? t('common.loading') : t('actions.addRule')}
			</button>
		</div>
	{/if}

	{#each rules as rule}
		<div class="border border-[var(--color-border)] rounded-md p-3 {!rule.enabled ? 'opacity-60' : ''}">
			<div class="flex items-center justify-between">
				<button onclick={() => expandedRule = expandedRule === rule.id ? null : rule.id}
					class="flex items-center gap-2 text-sm font-medium text-left flex-1">
					<MdiIcon name={expandedRule === rule.id ? 'mdiChevronDown' : 'mdiChevronRight'} size={16} />
					{rule.name || t('actions.unnamedRule')}
				</button>
				<div class="flex items-center gap-1">
					<button onclick={() => toggleRule(rule)}
						class="text-xs px-1.5 py-0.5 rounded {rule.enabled ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'}">
						{rule.enabled ? t('actions.on') : t('actions.off')}
					</button>
					<IconButton icon="mdiDelete" title={t('common.delete')} onclick={() => deleteRule(rule.id)} variant="danger" size={16} />
				</div>
			</div>

			{#if expandedRule === rule.id}
				<div class="mt-2 pt-2 border-t border-[var(--color-border)] space-y-2">
					<div>
						<label class="block text-xs font-medium mb-1">{t('actions.ruleName')}</label>
						<input bind:value={rule.name}
							class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
					</div>

					{#if actionType === 'auto_organize'}
						{@render criteriaFields(rule.rule_config)}
					{/if}

					<button onclick={() => updateRule(rule)}
						class="text-xs px-3 py-1.5 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded hover:opacity-90">
						{t('common.save')}
					</button>
				</div>
			{/if}
		</div>
	{/each}

	{#if rules.length === 0 && !loading && !showAddForm}
		<p class="text-sm text-[var(--color-muted-foreground)] text-center py-2">{t('actions.noRules')}</p>
	{/if}
</div>

{#snippet criteriaFields(ruleConfig: any)}
	<fieldset class="space-y-2 pl-2 border-l-2 border-[var(--color-border)]">
		<legend class="text-xs font-semibold text-[var(--color-muted-foreground)] mb-1">{t('actions.criteria')}</legend>

		<!-- Person selector -->
		{#if personItems.length > 0}
		<div>
			<label class="block text-xs font-medium mb-1">{t('actions.persons')}</label>
			<MultiEntitySelect items={personItems}
				bind:values={ruleConfig.criteria.person_ids}
				placeholder={t('actions.addPerson')}
				size="sm"
				onchange={(ids) => {
					ruleConfig.criteria.person_names = ids.map(id => people.find(p => p.id === id)?.name || id);
				}} />
		</div>
		{/if}

		<!-- Smart search query -->
		<div>
			<label class="block text-xs font-medium mb-1">{t('actions.searchQuery')}</label>
			<input bind:value={ruleConfig.criteria.query} placeholder={t('actions.searchQueryPlaceholder')}
				class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
		</div>

		<!-- Asset type -->
		<div class="flex items-center gap-3">
			<label class="text-xs font-medium">{t('actions.assetType')}:</label>
			{#each ['all', 'image', 'video'] as at}
				<label class="flex items-center gap-1 text-xs">
					<input type="radio"
						checked={ruleConfig.criteria.asset_type === at}
						onchange={() => { ruleConfig.criteria.asset_type = at; }}
						class="accent-[var(--color-primary)]" />
					{at}
				</label>
			{/each}
		</div>

		<!-- Date range -->
		<div class="flex gap-2">
			<div class="flex-1">
				<label class="block text-xs font-medium mb-1">{t('actions.dateFrom')}</label>
				<input type="date" bind:value={ruleConfig.criteria.date_from}
					class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
			</div>
			<div class="flex-1">
				<label class="block text-xs font-medium mb-1">{t('actions.dateTo')}</label>
				<input type="date" bind:value={ruleConfig.criteria.date_to}
					class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
			</div>
		</div>

		<!-- Favorites only -->
		<label class="flex items-center gap-2 text-xs">
			<input type="checkbox" bind:checked={ruleConfig.criteria.favorite_only} class="accent-[var(--color-primary)]" />
			{t('actions.favoritesOnly')}
		</label>
	</fieldset>

	<!-- Target album -->
	<fieldset class="space-y-2 pl-2 border-l-2 border-[var(--color-border)]">
		<legend class="text-xs font-semibold text-[var(--color-muted-foreground)] mb-1">{t('actions.targetAlbum')}</legend>

		{#if albumItems.length > 0}
		<div>
			<label class="block text-xs font-medium mb-1">{t('actions.selectAlbum')}</label>
			<MultiEntitySelect items={albumItems}
				bind:values={ruleConfig.target_album_ids}
				placeholder={t('actions.selectAlbumPlaceholder')}
				size="sm"
				onchange={(ids) => {
					ruleConfig.target_album_names = ids.map(id => albums.find(a => a.id === id)?.name || id);
				}} />
		</div>
		{:else}
		<div>
			<label class="block text-xs font-medium mb-1">{t('actions.albumId')}</label>
			<input bind:value={ruleConfig.target_album_id}
				class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)] font-mono" />
		</div>
		{/if}

		<label class="flex items-center gap-2 text-xs">
			<input type="checkbox" bind:checked={ruleConfig.create_album_if_missing} class="accent-[var(--color-primary)]" />
			{t('actions.createAlbumIfMissing')}
		</label>

		{#if ruleConfig.create_album_if_missing}
		<div>
			<label class="block text-xs font-medium mb-1">{t('actions.newAlbumName')}</label>
			<input bind:value={ruleConfig.create_album_name}
				class="w-full px-2 py-1.5 border border-[var(--color-border)] rounded text-sm bg-[var(--color-background)]" />
		</div>
		{/if}
	</fieldset>
{/snippet}
