<script lang="ts">
	import { t } from '$lib/i18n';
	import { api , errMsg} from '$lib/api';
	import { snackError, snackSuccess } from '$lib/stores/snackbar.svelte';
	import Modal from '$lib/components/Modal.svelte';
	import MdiIcon from '$lib/components/MdiIcon.svelte';

	interface AlbumIssue { id: string; name: string; issue: string }

	interface Props {
		linkWarning: { albums: AlbumIssue[]; providerId: number } | null;
		linkCreating: boolean;
		onclose: () => void;
		onautoCreate: () => void;
		ondismiss: () => void;
		/** Called with the updated warning list after a per-row replace. */
		onupdate?: (albums: AlbumIssue[]) => void;
	}

	let { linkWarning, linkCreating, onclose, onautoCreate, ondismiss, onupdate }: Props = $props();

	/** Per-row loading state for the "Replace" button. */
	let replacing = $state<Record<string, boolean>>({});

	/**
	 * Expired and password-protected links can't be repaired in place вЂ” the
	 * Immich API has no "reset" endpoint. The only remedy is to recreate the
	 * link (which the backend does by POSTing a new one and returning it).
	 * We surface the action per-row so users don't have to leave the form.
	 */
	async function replaceOne(album: AlbumIssue) {
		if (!linkWarning) return;
		replacing = { ...replacing, [album.id]: true };
		try {
			await api(`/providers/${linkWarning.providerId}/albums/${album.id}/shared-links`, {
				method: 'POST',
				body: JSON.stringify({ replace: true }),
			});
			snackSuccess(t('notificationTracker.createdLinks').replace('{count}', '1'));
			const remaining = linkWarning.albums.filter(a => a.id !== album.id);
			if (onupdate) onupdate(remaining);
		} catch (err: unknown) {
			snackError(t('notificationTracker.linkReplaceFailed').replace('{name}', album.name) + ': ' + errMsg(err));
		} finally {
			replacing = { ...replacing, [album.id]: false };
		}
	}
</script>

<Modal open={linkWarning !== null} title={t('notificationTracker.missingLinksTitle')} onclose={onclose}>
	{#if linkWarning}
		<p class="text-sm mb-3" style="color: var(--color-muted-foreground);">
			{t('notificationTracker.missingLinksDesc')}
		</p>
		<div class="space-y-1.5 mb-4 max-h-60 overflow-y-auto">
			{#each linkWarning.albums as album}
				<div class="flex items-center justify-between gap-2 text-sm px-2 py-1.5 rounded bg-[var(--color-muted)]/30">
					<div class="flex-1 min-w-0">
						<span class="font-medium truncate block">{album.name}</span>
						{#if album.issue === 'password-protected'}
							<span class="text-[10px] block" style="color: var(--color-muted-foreground);">
								{t('notificationTracker.linkPasswordProtectedNote')}
							</span>
						{/if}
					</div>
					<span class="text-xs px-1.5 py-0.5 rounded shrink-0 {album.issue === 'expired' ? 'bg-[var(--color-error-bg)] text-[var(--color-error-fg)]' : album.issue === 'password-protected' ? 'bg-[var(--color-warning-bg)] text-[var(--color-warning-fg)]' : 'bg-[var(--color-muted)] text-[var(--color-muted-foreground)]'}">
						{album.issue === 'expired' ? t('notificationTracker.expired') : album.issue === 'password-protected' ? t('notificationTracker.passwordProtected') : t('notificationTracker.noLink')}
					</span>
					{#if album.issue === 'expired' || album.issue === 'password-protected'}
						<button type="button" onclick={() => replaceOne(album)} disabled={replacing[album.id]}
							class="text-xs px-2 py-1 rounded border border-[var(--color-border)] hover:bg-[var(--color-muted)] disabled:opacity-50 shrink-0">
							{replacing[album.id] ? t('notificationTracker.linkReplacing') : t('notificationTracker.linkReplace')}
						</button>
					{/if}
				</div>
			{/each}
		</div>
		<p class="text-xs mb-4" style="color: var(--color-muted-foreground);">
			<MdiIcon name="mdiInformation" size={14} /> {t('notificationTracker.linksNote')}
		</p>
		<div class="flex items-center gap-2 justify-end">
			<button onclick={ondismiss}
				class="px-3 py-1.5 text-sm border border-[var(--color-border)] rounded-md hover:bg-[var(--color-muted)]">
				{t('notificationTracker.saveWithoutLinks')}
			</button>
			{#if linkWarning.albums.some(a => a.issue === 'missing')}
				<button onclick={onautoCreate} disabled={linkCreating}
					class="px-3 py-1.5 text-sm bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md hover:opacity-90 disabled:opacity-50">
					{linkCreating ? t('common.loading') : t('notificationTracker.createLinks').replace('{count}', String(linkWarning.albums.filter(a => a.issue === 'missing').length))}
				</button>
			{/if}
		</div>
	{/if}
</Modal>
