<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import { slide } from 'svelte/transition';
	import { api , errMsg} from '$lib/api';
	import { topbarAction } from '$lib/stores/topbar-action.svelte';
	import { t } from '$lib/i18n';
	import { providersCache, telegramBotsCache, commandConfigsCache } from '$lib/stores/caches.svelte';
	import PageHeader from '$lib/components/PageHeader.svelte';
	import Card from '$lib/components/Card.svelte';
	import Loading from '$lib/components/Loading.svelte';
	import IconPicker from '$lib/components/IconPicker.svelte';
	import MdiIcon from '$lib/components/MdiIcon.svelte';
	import EmptyState from '$lib/components/EmptyState.svelte';
	import ConfirmModal from '$lib/components/ConfirmModal.svelte';
	import Modal from '$lib/components/Modal.svelte';
	import IconButton from '$lib/components/IconButton.svelte';
	import CrossLink from '$lib/components/CrossLink.svelte';
	import EntitySelect from '$lib/components/EntitySelect.svelte';
	import { snackSuccess, snackError } from '$lib/stores/snackbar.svelte';
	import { highlightFromUrl } from '$lib/highlight';
	import { globalProviderFilter } from '$lib/stores/provider-filter.svelte';
	import { providerDefaultIcon } from '$lib/grid-items';
	import Button from '$lib/components/Button.svelte';
	import MetaStrip, { type MetaTile } from '$lib/components/MetaStrip.svelte';
	import type { ServiceProvider, TelegramBot } from '$lib/types';

	let allCmdTrackers = $state<any[]>([]);
	let filterText = $state('');
	let filterProviderId = $state(0);
	let effectiveProviderId = $derived(globalProviderFilter.id || filterProviderId);
	let trackers = $derived(allCmdTrackers.filter((t: any) =>
		(!filterText || t.name.toLowerCase().includes(filterText.toLowerCase())) &&
		(!effectiveProviderId || t.provider_id === effectiveProviderId)
	));
	let providers = $derived(providersCache.items);
	let commandConfigs = $derived(commandConfigsCache.items);
	let telegramBots = $derived(telegramBotsCache.items);
	const providerItems = $derived(providers
		.filter(p => !globalProviderFilter.providerType || p.type === globalProviderFilter.providerType)
		.map(p => ({ value: p.id, label: p.name, icon: providerDefaultIcon(p), desc: p.type })));
	const botItems = $derived(telegramBots.map(b => ({ value: b.id, label: b.name, icon: b.icon || 'mdiRobot', desc: b.bot_username ? `@${b.bot_username}` : '' })));
	let loaded = $state(false);
	let showForm = $state(false);
	let editing = $state<number | null>(null);
	let error = $state('');
	let submitting = $state(false);
	let confirmDelete = $state<any>(null);
	let toggling = $state<Record<number, boolean>>({});

	// Listeners per tracker
	let listeners = $state<Record<number, any[]>>({});
	let listenersLoading = $state<Record<number, boolean>>({});
	let expandedTracker = $state<number | null>(null);
	let addingListener = $state<Record<number, boolean>>({});
	let newListenerBotId = $state<Record<number, number>>({});

	const defaultForm = () => ({
		name: '',
		icon: '',
		provider_id: 0,
		command_config_id: 0,
		enabled: true,
	});
	let form = $state(defaultForm());
	let nameManuallyEdited = $state(false);

	$effect(() => {
		if (showForm && !nameManuallyEdited && !editing) {
			const provider = providers.find(p => p.id === form.provider_id);
			form.name = provider ? `${provider.name} Commands` : 'Commands';
		}
	});

	// Filter command configs by selected provider's type
	let filteredConfigs = $derived.by(() => {
		if (!form.provider_id) return commandConfigs;
		const provider = providers.find(p => p.id === form.provider_id);
		if (!provider) return commandConfigs;
		return commandConfigs.filter(c => c.provider_type === provider.type);
	});
	const configItems = $derived(filteredConfigs
		.filter((c: any) => !globalProviderFilter.providerType || c.provider_type === globalProviderFilter.providerType)
		.map((c: any) => ({ value: c.id, label: c.name, icon: c.icon || 'mdiCog', desc: c.provider_type })));

	onMount(() => {
		topbarAction.set({
			label: t('commandTracker.newTracker'),
			onclick: () => { showForm ? (showForm = false, editing = null) : openNew(); },
		});
		load();
	});
	onDestroy(() => topbarAction.clear());

	const headerPills = $derived.by(() => {
		const pills: Array<{ label: string; tone: 'mint' | 'sky' | 'citrus' }> = [];
		const armed = trackers.filter((tr: { enabled?: boolean }) => tr.enabled).length;
		const paused = trackers.length - armed;
		if (armed > 0) pills.push({ label: `${armed} ${t('notificationTracker.armed')}`, tone: 'mint' });
		if (paused > 0) pills.push({ label: `${paused} ${t('notificationTracker.paused')}`, tone: 'citrus' });
		return pills;
	});

	async function load() {
		try {
			[allCmdTrackers] = await Promise.all([
				api('/command-trackers'),
				providersCache.fetch(), commandConfigsCache.fetch(),
				telegramBotsCache.fetch(),
			]);
		} catch (err: unknown) { error = errMsg(err, t('common.loadError')); snackError(error); }
		finally { loaded = true; highlightFromUrl(); }
	}

	function openNew() {
		form = defaultForm();
		if (providers.length > 0) form.provider_id = providers[0].id;
		const ptype = providers.find(p => p.id === form.provider_id)?.type || '';
		if (ptype) {
			const firstCfg = commandConfigs.find(c => c.provider_type === ptype);
			if (firstCfg) form.command_config_id = firstCfg.id;
		}
		nameManuallyEdited = false;
		editing = null;
		showForm = true;
	}

	// Re-pick the command config when the provider changes. The previously
	// selected id may belong to a different provider type and would no longer
	// appear in the filtered EntitySelect, leaving the selector empty.
	let _prevProviderId = $state(0);
	$effect(() => {
		if (showForm && form.provider_id && form.provider_id !== _prevProviderId) {
			_prevProviderId = form.provider_id;
			if (editing === null) {
				const ptype = providers.find(p => p.id === form.provider_id)?.type || '';
				if (ptype) {
					const currentCfg = commandConfigs.find(c => c.id === form.command_config_id);
					if (!currentCfg || currentCfg.provider_type !== ptype) {
						const first = commandConfigs.find(c => c.provider_type === ptype);
						form.command_config_id = first?.id ?? 0;
					}
				}
			}
		}
	});
	function editTracker(trk: any) {
		form = {
			name: trk.name,
			icon: trk.icon || '',
			provider_id: trk.provider_id,
			command_config_id: trk.command_config_id,
			enabled: trk.enabled,
		};
		nameManuallyEdited = true;
		editing = trk.id;
		showForm = true;
	}

	async function saveTracker(e: SubmitEvent) {
		e.preventDefault(); error = ''; submitting = true;
		try {
			const body = JSON.stringify(form);
			if (editing) {
				await api(`/command-trackers/${editing}`, { method: 'PUT', body });
				snackSuccess(t('snack.commandTrackerUpdated'));
			} else {
				await api('/command-trackers', { method: 'POST', body });
				snackSuccess(t('snack.commandTrackerCreated'));
			}
			form = defaultForm(); nameManuallyEdited = false; showForm = false; editing = null; await load();
		} catch (err: unknown) { const __m = errMsg(err); error = __m; snackError(__m); }
		finally { submitting = false; }
	}

	function remove(trk: any) {
		confirmDelete = {
			id: trk.id,
			onconfirm: async () => {
				try {
					await api(`/command-trackers/${trk.id}`, { method: 'DELETE' });
					await load();
					snackSuccess(t('snack.commandTrackerDeleted'));
				} catch (err: unknown) { snackError(errMsg(err)); }
				finally { confirmDelete = null; }
			}
		};
	}

	async function toggleEnabled(trk: any) {
		toggling = { ...toggling, [trk.id]: true };
		try {
			const endpoint = trk.enabled ? 'disable' : 'enable';
			await api(`/command-trackers/${trk.id}/${endpoint}`, { method: 'POST' });
			snackSuccess(trk.enabled ? t('snack.commandTrackerDisabled') : t('snack.commandTrackerEnabled'));
			await load();
		} catch (err: unknown) { snackError(errMsg(err)); }
		toggling = { ...toggling, [trk.id]: false };
	}

	function toggleListeners(trkId: number) {
		if (expandedTracker === trkId) {
			expandedTracker = null;
			return;
		}
		expandedTracker = trkId;
		loadListeners(trkId);
	}

	async function loadListeners(trkId: number) {
		listenersLoading = { ...listenersLoading, [trkId]: true };
		try {
			listeners = { ...listeners, [trkId]: await api(`/command-trackers/${trkId}/listeners`) };
		} catch { listeners = { ...listeners, [trkId]: [] }; }
		listenersLoading = { ...listenersLoading, [trkId]: false };
	}

	async function addListener(trkId: number) {
		const botId = newListenerBotId[trkId];
		if (!botId) return;
		addingListener = { ...addingListener, [trkId]: true };
		try {
			await api(`/command-trackers/${trkId}/listeners`, {
				method: 'POST',
				body: JSON.stringify({ listener_type: 'telegram_bot', listener_id: botId }),
			});
			snackSuccess(t('snack.listenerAdded'));
			await loadListeners(trkId);
			newListenerBotId = { ...newListenerBotId, [trkId]: 0 };
		} catch (err: unknown) { snackError(errMsg(err)); }
		addingListener = { ...addingListener, [trkId]: false };
	}

	async function removeListener(trkId: number, listenerId: number) {
		try {
			await api(`/command-trackers/${trkId}/listeners/${listenerId}`, { method: 'DELETE' });
			snackSuccess(t('snack.listenerRemoved'));
			await loadListeners(trkId);
		} catch (err: unknown) { snackError(errMsg(err)); }
	}

	// Per-listener album scope editing
	let scopeEditor = $state<{ trkId: number; listener: any; providerId: number; collections: any[]; selectedIds: string[]; inherit: boolean } | null>(null);
	async function openScopeEditor(trkId: number, listener: any) {
		const trk = allCmdTrackers.find((t: any) => t.id === trkId);
		if (!trk) return;
		let collections: any[] = [];
		try { collections = await api(`/providers/${trk.provider_id}/collections`); } catch { /* ignore */ }
		scopeEditor = {
			trkId,
			listener,
			providerId: trk.provider_id,
			collections,
			selectedIds: [...(listener.allowed_album_ids || [])],
			inherit: listener.allowed_album_ids === null || listener.allowed_album_ids === undefined,
		};
	}
	async function saveScope() {
		if (!scopeEditor) return;
		const body = { allowed_album_ids: scopeEditor.inherit ? null : scopeEditor.selectedIds };
		try {
			await api(`/command-trackers/${scopeEditor.trkId}/listeners/${scopeEditor.listener.id}`, {
				method: 'PATCH', body: JSON.stringify(body),
			});
			snackSuccess(t('snack.listenerScopeSaved'));
			await loadListeners(scopeEditor.trkId);
			scopeEditor = null;
		} catch (err: unknown) { snackError(errMsg(err)); }
	}

	function providerName(id: number): string {
		return providers.find(p => p.id === id)?.name || '?';
	}
	function configName(id: number): string {
		return commandConfigs.find(c => c.id === id)?.name || '?';
	}

	function commandTrackerTiles(trk: any): MetaTile[] {
		const tiles: MetaTile[] = [];
		tiles.push(trk.enabled
			? { icon: 'mdiCheckCircle', label: t('commandTracker.enabled'), tone: 'mint' }
			: { icon: 'mdiCloseCircle', label: t('commandTracker.disabled'), tone: 'coral' });
		tiles.push({
			icon: 'mdiServer',
			label: providerName(trk.provider_id),
			tone: 'lavender',
		});
		tiles.push({
			icon: 'mdiCog',
			label: configName(trk.command_config_id),
			tone: 'sky',
		});
		if (trk.listener_count !== undefined) {
			tiles.push({
				icon: 'mdiAccountMultipleOutline',
				value: String(trk.listener_count),
				label: t('commandTracker.listeners').toLowerCase(),
				tone: trk.listener_count > 0 ? 'orchid' : 'default',
			});
		}
		return tiles;
	}
</script>

<PageHeader
	title={t('commandTracker.title')}
	emphasis={t('commandTracker.titleEmphasis')}
	description={t('commandTracker.description')}
	crumb={t('crumbs.routingCommands')}
	count={trackers.length}
	countLabel={t('dashboard.trackersShort')}
	pills={headerPills}
>
	<Button size="sm" onclick={() => { showForm ? (showForm = false, editing = null) : openNew(); }}>
		{showForm ? t('common.cancel') : t('commandTracker.newTracker')}
	</Button>
</PageHeader>

{#if !loaded}<Loading />{:else}

{#if showForm}
	<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={saveTracker} class="space-y-3">
			<div>
				<label for="trk-name" class="block text-sm font-medium mb-1">{t('commandTracker.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} oninput={() => nameManuallyEdited = true} required placeholder={t('commandTracker.namePlaceholder')}
						class="flex-1 px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
				</div>
			</div>

			<div>
				<div class="block text-sm font-medium mb-1">{t('commandTracker.provider')}</div>
				<EntitySelect items={providerItems} bind:value={form.provider_id} placeholder={t('commandTracker.selectProvider')} />
			</div>

			<div>
				<div class="block text-sm font-medium mb-1">{t('commandTracker.commandConfig')}</div>
				<EntitySelect items={configItems} bind:value={form.command_config_id} placeholder={t('commandTracker.selectCommandConfig')} />
			</div>

			<Button type="submit" disabled={submitting}>
				{submitting ? t('common.loading') : (editing ? t('common.save') : t('common.create'))}
			</Button>
		</form>
	</Card>
{/if}

{#if !showForm && allCmdTrackers.length > 0}
<div class="flex items-center gap-2 mb-3">
	<input type="text" bind:value={filterText} placeholder={t('common.filterByName')}
		class="flex-1 px-3 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
	{#if !globalProviderFilter.id}
	<div class="w-48">
		<EntitySelect items={[{value: 0, label: t('common.allProviders'), icon: 'mdiFilterOff'}, ...providerItems]} bind:value={filterProviderId} placeholder={t('common.allProviders')} />
	</div>
	{/if}
</div>
{/if}

{#if allCmdTrackers.length === 0 && !showForm}
	<Card>
		<EmptyState icon="mdiConsoleLine" message={t('commandTracker.noTrackers')} />
	</Card>
{:else if trackers.length === 0 && !showForm}
	<Card>
		<EmptyState icon="mdiFilterOff" message={t('common.noFilterResults')} />
	</Card>
{:else}
	<div class="list-stack stagger-children">
		{#each trackers as trk}
			<Card hover entityId={trk.id}>
				<div class="list-row">
					<div class="list-row__identity">
						<div class="flex items-center gap-2 min-w-0">
							<span style="color: var(--color-primary);" class="shrink-0"><MdiIcon name={trk.icon || 'mdiConsoleLine'} size={20} /></span>
							<p class="font-medium truncate">{trk.name}</p>
							<span class="text-xs px-1.5 py-0.5 rounded font-mono shrink-0 {trk.enabled
								? 'bg-[var(--color-success-bg)] text-[var(--color-success-fg)]'
								: 'bg-[var(--color-error-bg)] text-[var(--color-error-fg)]'}">
								{trk.enabled ? t('commandTracker.enabled') : t('commandTracker.disabled')}
							</span>
						</div>
						<div class="list-row__secondary mt-0.5 flex items-center gap-2 flex-wrap">
							<CrossLink href="/providers" icon="mdiServer" label={providerName(trk.provider_id)} entityId={trk.provider_id} />
							<CrossLink href="/command-configs" icon="mdiCog" label={configName(trk.command_config_id)} entityId={trk.command_config_id} />
							{#if trk.listener_count !== undefined}
								<span class="text-xs text-[var(--color-muted-foreground)]">
									{trk.listener_count} {t('commandTracker.listeners').toLowerCase()}
								</span>
							{/if}
						</div>
					</div>
					<MetaStrip tiles={commandTrackerTiles(trk)} />
					<div class="list-row__actions flex-wrap justify-end">
						<IconButton icon="mdiPencil" title={t('common.edit')} onclick={() => editTracker(trk)} />
						<IconButton icon={trk.enabled ? 'mdiPause' : 'mdiPlay'} title={trk.enabled ? t('notificationTracker.pause') : t('notificationTracker.resume')} onclick={() => toggleEnabled(trk)} disabled={toggling[trk.id]} />
						<button onclick={() => toggleListeners(trk.id)}
							class="text-xs text-[var(--color-muted-foreground)] hover:underline px-2 py-1">
							{t('commandTracker.listeners')} {expandedTracker === trk.id ? 'в–І' : 'в–ј'}
						</button>
						<IconButton icon="mdiDelete" title={t('common.delete')} onclick={() => remove(trk)} variant="danger" />
					</div>
				</div>

				<!-- Listeners section -->
				{#if expandedTracker === trk.id}
					<div class="mt-3 border-t border-[var(--color-border)] pt-3" transition:slide>
						{#if listenersLoading[trk.id]}
							<p class="text-xs text-[var(--color-muted-foreground)]">{t('common.loading')}</p>
						{:else if (listeners[trk.id] || []).length === 0}
							<p class="text-xs text-[var(--color-muted-foreground)]">{t('commandTracker.noListeners')}</p>
						{:else}
							<div class="space-y-1">
								{#each listeners[trk.id] as listener}
									<div class="flex items-center justify-between text-sm px-2 py-1 rounded hover:bg-[var(--color-muted)]">
										<div class="flex items-center gap-2 min-w-0">
											<MdiIcon name="mdiRobot" size={14} />
											<CrossLink href="/bots?tab=telegram" icon="mdiRobot" label={listener.name || listener.listener_type} entityId={listener.listener_id} />
											<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-primary)]/10 text-[var(--color-primary)] font-mono">{listener.listener_type}</span>
											<button type="button" onclick={() => openScopeEditor(trk.id, listener)}
												class="flex items-center gap-1 text-xs px-1.5 py-0.5 rounded border border-[var(--color-border)] text-[var(--color-muted-foreground)] hover:bg-[var(--color-muted)]"
												title={t('commandTracker.editScope')}>
												<MdiIcon name="mdiImageMultiple" size={12} />
												{listener.allowed_album_ids === null || listener.allowed_album_ids === undefined
													? t('commandTracker.scopeAll')
													: `${(listener.allowed_album_ids || []).length} ${t('commandTracker.albumsShort')}`}
											</button>
										</div>
										<IconButton icon="mdiClose" title={t('commandTracker.removeListener')} size={14}
											onclick={() => removeListener(trk.id, listener.id)} variant="danger" />
									</div>
								{/each}
							</div>
						{/if}

						<!-- Add listener -->
						<div class="flex items-center gap-2 mt-2">
							<div class="flex-1">
								<EntitySelect items={botItems} bind:value={newListenerBotId[trk.id]} placeholder={t('commandTracker.selectBot')} />
							</div>
							<Button size="sm" onclick={() => addListener(trk.id)} disabled={!newListenerBotId[trk.id] || addingListener[trk.id]}>
								{addingListener[trk.id] ? t('common.loading') : t('commandTracker.addListener')}
							</Button>
						</div>
					</div>
				{/if}
			</Card>
		{/each}
	</div>
{/if}

{/if}

<ConfirmModal open={confirmDelete !== null} message={t('commandTracker.confirmDelete')}
	onconfirm={() => confirmDelete?.onconfirm()} oncancel={() => confirmDelete = null} />

<!-- Per-listener album scope editor -->
<Modal open={scopeEditor !== null} title={t('commandTracker.scopeTitle')} onclose={() => scopeEditor = null}>
	{#if scopeEditor}
		<p class="text-xs text-[var(--color-muted-foreground)] mb-3">{t('commandTracker.scopeDescription')}</p>
		<label class="flex items-center gap-2 text-sm mb-3">
			<input type="checkbox" bind:checked={scopeEditor.inherit} />
			{t('commandTracker.scopeInherit')}
		</label>
		{#if !scopeEditor.inherit}
			{#if scopeEditor.collections.length > 0}
				<div class="flex items-center justify-between mb-1.5 text-xs" style="color: var(--color-muted-foreground);">
					<span>{scopeEditor.selectedIds.length} / {scopeEditor.collections.length}</span>
					<div class="flex items-center gap-2">
						<button type="button" class="underline hover:text-[var(--color-primary)]"
							onclick={() => { if (scopeEditor) scopeEditor.selectedIds = scopeEditor.collections.map((c: any) => c.id); }}>
							{t('backup.selectAll')}
						</button>
						<span aria-hidden="true">В·</span>
						<button type="button" class="underline hover:text-[var(--color-primary)]"
							onclick={() => { if (scopeEditor) scopeEditor.selectedIds = []; }}>
							{t('backup.deselectAll')}
						</button>
					</div>
				</div>
			{/if}
			<div class="space-y-1 max-h-72 overflow-y-auto border border-[var(--color-border)] rounded-md p-2">
				{#if scopeEditor.collections.length === 0}
					<p class="text-xs text-[var(--color-muted-foreground)] py-3 text-center">{t('commandTracker.noCollections')}</p>
				{:else}
					{#each scopeEditor.collections as col}
						{@const cid = col.id}
						<label class="flex items-center gap-2 text-sm px-2 py-1 rounded hover:bg-[var(--color-muted)] cursor-pointer">
							<input type="checkbox" checked={scopeEditor.selectedIds.includes(cid)}
								onchange={(e) => {
									if (!scopeEditor) return;
									const target = e.target as HTMLInputElement;
									scopeEditor.selectedIds = target.checked
										? [...scopeEditor.selectedIds, cid]
										: scopeEditor.selectedIds.filter((i) => i !== cid);
								}} />
							<span class="truncate min-w-0 flex-1" title={col.albumName || col.name || cid}>{col.albumName || col.name || cid}</span>
						</label>
					{/each}
				{/if}
			</div>
		{/if}
		<div class="flex gap-2 justify-end mt-4">
			<button onclick={() => scopeEditor = null}
				class="px-3 py-1.5 text-sm rounded-md border border-[var(--color-border)] hover:bg-[var(--color-muted)] transition-colors">
				{t('common.cancel')}
			</button>
			<Button size="sm" onclick={saveScope}>{t('common.save')}</Button>
		</div>
	{/if}
</Modal>
