<script lang="ts">
	import { t } from '$lib/i18n';
	import { api, parseDate } from '$lib/api';
	import MdiIcon from '$lib/components/MdiIcon.svelte';
	import ConfirmModal from '$lib/components/ConfirmModal.svelte';
	import type { WebhookPayloadLog } from '$lib/types';

	interface Props {
		providerId: number;
	}
	let { providerId }: Props = $props();

	let logs = $state<WebhookPayloadLog[]>([]);
	let loading = $state(false);
	let loaded = $state(false);
	let expanded = $state(false);
	let expandedId = $state<number | null>(null);
	let showClearConfirm = $state(false);

	async function loadLogs() {
		loading = true;
		try {
			logs = await api(`/providers/${providerId}/webhook-logs`);
		} catch (e) {
			console.error('Failed to load webhook logs', e);
			logs = [];
		}
		loading = false;
		loaded = true;
	}

	function toggle() {
		expanded = !expanded;
		if (expanded && !loaded) loadLogs();
	}

	async function clearLogs() {
		try {
			await api(`/providers/${providerId}/webhook-logs`, { method: 'DELETE' });
			logs = [];
		} catch (e) { console.error('Failed to clear webhook logs', e); }
		showClearConfirm = false;
	}

	function toggleExpand(id: number) {
		expandedId = expandedId === id ? null : id;
	}

	function statusColor(status: string): string {
		if (status === 'matched') return 'var(--color-success-fg)';
		if (status === 'unmatched') return 'var(--color-warning-fg)';
		return 'var(--color-error-fg)';
	}

	function statusIcon(status: string): string {
		if (status === 'matched') return 'mdiCheckCircle';
		if (status === 'unmatched') return 'mdiMinusCircle';
		return 'mdiAlertCircle';
	}

	function statusLabel(status: string): string {
		if (status === 'matched') return t('webhookLogs.statusMatched');
		if (status === 'unmatched') return t('webhookLogs.statusUnmatched');
		return t('webhookLogs.statusError');
	}

	function formatTime(iso: string): string {
		return parseDate(iso).toLocaleString();
	}
</script>

<div class="border-t border-[var(--color-border)] mt-3 pt-2">
	<button onclick={toggle} class="w-full flex items-center gap-2 text-sm font-medium py-1 hover:opacity-80 transition-opacity">
		<MdiIcon name={expanded ? 'mdiChevronDown' : 'mdiChevronRight'} size={16} />
		{t('webhookLogs.title')}
		{#if loaded && logs.length > 0}
			<span class="text-xs px-1.5 py-0.5 rounded-full bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{logs.length}</span>
		{/if}
	</button>

	{#if expanded}
		<div class="mt-2">
			{#if loading}
				<div class="text-sm text-[var(--color-muted-foreground)] py-3 text-center">{t('common.loading')}</div>
			{:else if logs.length === 0}
				<div class="text-sm text-[var(--color-muted-foreground)] py-3 text-center">{t('webhookLogs.empty')}</div>
			{:else}
				<div class="flex justify-end mb-2">
					<button
						onclick={() => showClearConfirm = true}
						class="text-xs px-2 py-1 rounded-md transition-colors hover:bg-[var(--color-error-bg)] text-[var(--color-error-fg)]"
					>
						{t('webhookLogs.clear')}
					</button>
				</div>
				<div class="space-y-1">
					{#each logs as log}
						<button
							onclick={() => toggleExpand(log.id)}
							class="w-full text-left px-3 py-2 rounded-md text-sm transition-colors hover:bg-[var(--color-sidebar-active)]"
							style="background: {expandedId === log.id ? 'var(--color-sidebar-active)' : 'transparent'};"
						>
							<div class="flex items-center gap-2">
								<MdiIcon name={expandedId === log.id ? 'mdiChevronDown' : 'mdiChevronRight'} size={14} />
								<span class="text-xs text-[var(--color-muted-foreground)] tabular-nums">{formatTime(log.created_at)}</span>
								<span class="text-xs font-mono px-1 py-0.5 rounded bg-[var(--color-muted)]">{log.method}</span>
								<span class="flex items-center gap-1" style="color: {statusColor(log.status)};">
									<MdiIcon name={statusIcon(log.status)} size={14} />
									<span class="text-xs font-medium">{statusLabel(log.status)}</span>
								</span>
								{#if log.error_message && log.status === 'error'}
									<span class="text-xs text-[var(--color-muted-foreground)] truncate max-w-[200px]">{log.error_message}</span>
								{/if}
							</div>
						</button>

						{#if expandedId === log.id}
							<div class="ml-6 mr-2 mb-2 space-y-2">
								{#if Object.keys(log.headers).length > 0}
									<div>
										<div class="text-xs font-medium text-[var(--color-muted-foreground)] mb-1">{t('webhookLogs.headers')}</div>
										<div class="bg-[var(--color-background)] border border-[var(--color-border)] rounded-md p-2 text-xs font-mono">
											{#each Object.entries(log.headers) as [key, value]}
												<div><span class="text-[var(--color-primary)]">{key}</span>: {value}</div>
											{/each}
										</div>
									</div>
								{/if}

								<div>
									<div class="text-xs font-medium text-[var(--color-muted-foreground)] mb-1">{t('webhookLogs.body')}</div>
									<pre class="bg-[var(--color-background)] border border-[var(--color-border)] rounded-md p-2 text-xs font-mono overflow-x-auto whitespace-pre-wrap break-all" style="max-height: 300px; overflow-y: auto;">{JSON.stringify(log.body, null, 2)}</pre>
								</div>

								{#if log.status === 'matched' && Object.keys(log.extracted_fields).length > 0}
									<div>
										<div class="text-xs font-medium text-[var(--color-muted-foreground)] mb-1">{t('webhookLogs.extractedFields')}</div>
										<div class="bg-[var(--color-background)] border border-[var(--color-border)] rounded-md p-2 text-xs font-mono">
											{#each Object.entries(log.extracted_fields) as [key, value]}
												<div><span class="text-[var(--color-primary)]">{key}</span>: {typeof value === 'object' ? JSON.stringify(value) : String(value)}</div>
											{/each}
										</div>
									</div>
								{/if}

								{#if log.status === 'error' && log.error_message}
									<div>
										<div class="text-xs font-medium text-[var(--color-error-fg)] mb-1">{t('webhookLogs.errorMessage')}</div>
										<div class="bg-[var(--color-error-bg)] text-[var(--color-error-fg)] rounded-md p-2 text-xs">{log.error_message}</div>
									</div>
								{/if}
							</div>
						{/if}
					{/each}
				</div>
			{/if}
		</div>
	{/if}
</div>

<ConfirmModal
	open={showClearConfirm}
	title={t('webhookLogs.clear')}
	message={t('webhookLogs.confirmClear')}
	onconfirm={clearLogs}
	oncancel={() => showClearConfirm = false}
/>
