<script lang="ts">
	import { getDnsRecords, syncDnsRecords, deleteDnsRecord, getSettings } from '$lib/api';
	import type { DnsRecordView } from '$lib/types';
	import { toasts } from '$lib/stores/toast';
	import { t } from '$lib/i18n';
	import { IconSearch, IconRefresh, IconTrash, IconLoader } from '$lib/components/icons';
	import Skeleton from '$lib/components/Skeleton.svelte';

	let loading = $state(true);
	let records = $state<DnsRecordView[]>([]);
	let wildcardDns = $state(true);
	let syncing = $state(false);

	// Filters
	let searchQuery = $state('');
	let filterConsumerType = $state('all');
	let filterStatus = $state('all');

	let filteredRecords = $derived.by(() => {
		let result = records;
		if (searchQuery) {
			const q = searchQuery.toLowerCase();
			result = result.filter(r => r.fqdn.toLowerCase().includes(q));
		}
		if (filterConsumerType !== 'all') {
			if (filterConsumerType === 'orphaned') {
				result = result.filter(r => r.consumer_type === '');
			} else {
				result = result.filter(r => r.consumer_type === filterConsumerType);
			}
		}
		if (filterStatus !== 'all') {
			result = result.filter(r => r.status === filterStatus);
		}
		return result;
	});

	async function loadRecords() {
		loading = true;
		try {
			const settings = await getSettings();
			wildcardDns = settings.wildcard_dns ?? true;
			records = await getDnsRecords();
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('dns.loadFailed'));
		} finally {
			loading = false;
		}
	}

	async function handleSync() {
		syncing = true;
		try {
			const result = await syncDnsRecords();
			toasts.success($t('dns.syncComplete', { created: String(result.created), deleted: String(result.deleted), synced: String(result.already_synced) }));
			await loadRecords();
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('dns.syncFailed'));
		} finally {
			syncing = false;
		}
	}

	async function handleDelete(fqdn: string) {
		try {
			await deleteDnsRecord(fqdn);
			toasts.success($t('dns.recordDeleted', { fqdn }));
			records = records.filter(r => r.fqdn !== fqdn);
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('dns.deleteFailed'));
		}
	}

	async function handleRefresh() {
		await loadRecords();
	}

	function statusColor(status: string): string {
		switch (status) {
			case 'synced': return 'badge-success';
			case 'missing': return 'badge-danger';
			case 'orphaned': return 'badge-warning';
			case 'wildcard': return 'badge-info';
			default: return 'badge-gray';
		}
	}

	$effect(() => { loadRecords(); });
</script>

<svelte:head>
	<title>{$t('dns.title')} - {$t('app.name')}</title>
</svelte:head>

<div class="space-y-6">
	{#if loading}
		<div class="space-y-4">
			<Skeleton height="2rem" width="12rem" />
			<Skeleton height="20rem" />
		</div>
	{:else}
		<!-- Header -->
		<div class="flex items-center justify-between">
			<div>
				<h1 class="text-xl font-bold text-[var(--text-primary)]">{$t('dns.title')}</h1>
				<p class="text-sm text-[var(--text-secondary)]">{$t('dns.description')}</p>
			</div>
			<div class="flex items-center gap-2">
				<button
					onclick={handleRefresh}
					class="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border-primary)] px-3 py-2 text-sm text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] transition-colors"
				>
					<IconRefresh size={16} />
					{$t('dns.refresh')}
				</button>
				{#if !wildcardDns}
					<button
						onclick={handleSync}
						disabled={syncing}
						class="inline-flex items-center gap-1.5 rounded-lg bg-[var(--color-brand-600)] px-3 py-2 text-sm font-medium text-white hover:bg-[var(--color-brand-700)] disabled:opacity-50 transition-colors"
					>
						{#if syncing}<IconLoader size={16} />{/if}
						{syncing ? $t('dns.syncing') : $t('dns.syncNow')}
					</button>
				{/if}
			</div>
		</div>

		<!-- Filters -->
		<div class="flex flex-wrap items-center gap-3">
			<div class="relative flex-1 min-w-[200px] max-w-sm">
				<IconSearch size={16} class="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-tertiary)]" />
				<input
					type="text"
					bind:value={searchQuery}
					placeholder={$t('dns.searchPlaceholder')}
					class="w-full rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] py-2 pl-9 pr-3 text-sm text-[var(--text-primary)] placeholder:text-[var(--text-tertiary)] focus:border-[var(--color-brand-500)] focus:outline-none focus:ring-1 focus:ring-[var(--color-brand-500)]"
				/>
			</div>
			<select bind:value={filterConsumerType}
				class="rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] px-3 py-2 text-sm text-[var(--text-primary)]">
				<option value="all">{$t('dns.allConsumers')}</option>
				<option value="instance">{$t('dns.managed')}</option>
				<option value="standalone">{$t('dns.standalone')}</option>
				<option value="orphaned">{$t('dns.orphaned')}</option>
			</select>
			{#if !wildcardDns}
			<select bind:value={filterStatus}
				class="rounded-lg border border-[var(--border-primary)] bg-[var(--surface-card)] px-3 py-2 text-sm text-[var(--text-primary)]">
				<option value="all">{$t('dns.allStatuses')}</option>
				<option value="synced">{$t('dns.statusSynced')}</option>
				<option value="missing">{$t('dns.statusMissing')}</option>
				<option value="orphaned">{$t('dns.statusOrphaned')}</option>
			</select>
		{/if}
		</div>

		<!-- Records Table -->
		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] shadow-[var(--shadow-sm)] overflow-hidden">
			{#if filteredRecords.length === 0}
				<div class="p-8 text-center text-sm text-[var(--text-tertiary)]">
					{records.length === 0 ? $t('dns.noRecords') : $t('dns.noMatchingRecords')}
				</div>
			{:else}
				<div class="overflow-x-auto">
					<table class="w-full text-sm">
						<thead>
							<tr class="border-b border-[var(--border-primary)] bg-[var(--surface-card-hover)]">
								<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnFqdn')}</th>
								<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnType')}</th>
								<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnValue')}</th>
								<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnConsumer')}</th>
								<th class="px-4 py-3 text-left font-medium text-[var(--text-secondary)]">{$t('dns.columnStatus')}</th>
								<th class="px-4 py-3 text-right font-medium text-[var(--text-secondary)]">{$t('dns.columnActions')}</th>
							</tr>
						</thead>
						<tbody>
							{#each filteredRecords as record}
								<tr class="border-b border-[var(--border-primary)] last:border-b-0 hover:bg-[var(--surface-card-hover)] transition-colors">
									<td class="px-4 py-3 font-mono text-xs text-[var(--text-primary)]">{record.fqdn}</td>
									<td class="px-4 py-3 text-[var(--text-secondary)]">{record.type}</td>
									<td class="px-4 py-3 font-mono text-xs text-[var(--text-secondary)]">{record.content}</td>
									<td class="px-4 py-3">
										{#if record.consumer_name}
											<span class="text-[var(--text-primary)]">{record.consumer_name}</span>
											<span class="ml-1 text-xs text-[var(--text-tertiary)]">({record.consumer_type})</span>
										{:else}
											<span class="text-[var(--text-tertiary)] italic">{$t('dns.noConsumer')}</span>
										{/if}
									</td>
									<td class="px-4 py-3">
										<span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium {statusColor(record.status)}">
											{record.status}
										</span>
									</td>
									<td class="px-4 py-3 text-right">
										{#if record.status === 'orphaned' || record.status === 'missing'}
											<button
												onclick={() => handleDelete(record.fqdn)}
												class="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-xs text-[var(--color-danger)] hover:bg-[var(--color-danger-light)] transition-colors"
												title={$t('dns.deleteRecord')}
											>
												<IconTrash size={14} />
											</button>
										{/if}
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			{/if}
		</div>

		<!-- Summary -->
		<div class="flex gap-4 text-xs text-[var(--text-tertiary)]">
			<span>{$t('dns.totalRecords', { count: String(records.length) })}</span>
			<span>{$t('dns.syncedCount', { count: String(records.filter(r => r.status === 'synced').length) })}</span>
			<span>{$t('dns.missingCount', { count: String(records.filter(r => r.status === 'missing').length) })}</span>
			<span>{$t('dns.orphanedCount', { count: String(records.filter(r => r.status === 'orphaned').length) })}</span>
		</div>
	{/if}
</div>
