<script lang="ts">
	import { page } from '$app/stores';
	import type { Volume } from '$lib/types';
	import * as api from '$lib/api';
	import { toasts } from '$lib/stores/toast';
	import { t } from '$lib/i18n';
	import { IconChevronRight, IconPlus, IconEdit, IconTrash, IconCheck, IconX, IconLoader } from '$lib/components/icons';
	import Skeleton from '$lib/components/Skeleton.svelte';
	import EmptyState from '$lib/components/EmptyState.svelte';

	let volumes = $state<Volume[]>([]);
	let loading = $state(true);
	let error = $state('');

	let newSource = $state('');
	let newTarget = $state('');
	let newMode = $state<'shared' | 'isolated'>('shared');
	let saving = $state(false);

	let editingId = $state('');
	let editSource = $state('');
	let editTarget = $state('');
	let editMode = $state<'shared' | 'isolated'>('shared');

	const projectId = $derived($page.params.id);

	async function loadVolumes() {
		loading = true;
		error = '';
		try {
			volumes = await api.listVolumes(projectId);
		} catch (e) {
			error = e instanceof Error ? e.message : $t('volumeEditor.loadFailed');
		} finally {
			loading = false;
		}
	}

	async function handleAdd() {
		if (!newSource.trim() || !newTarget.trim()) return;
		saving = true;
		try {
			await api.createVolume(projectId, { source: newSource.trim(), target: newTarget.trim(), mode: newMode });
			newSource = '';
			newTarget = '';
			newMode = 'shared';
			toasts.success($t('volumeEditor.volumeAdded'));
			await loadVolumes();
		} catch (e) {
			toasts.error(e instanceof Error ? e.message : $t('volumeEditor.addFailed'));
		} finally {
			saving = false;
		}
	}

	function startEdit(vol: Volume) {
		editingId = vol.id;
		editSource = vol.source;
		editTarget = vol.target;
		editMode = vol.mode;
	}

	function cancelEdit() { editingId = ''; }

	async function handleUpdate() {
		if (!editSource.trim() || !editTarget.trim()) return;
		saving = true;
		try {
			await api.updateVolume(projectId, editingId, { source: editSource.trim(), target: editTarget.trim(), mode: editMode });
			editingId = '';
			toasts.success($t('volumeEditor.volumeUpdated'));
			await loadVolumes();
		} catch (e) {
			toasts.error(e instanceof Error ? e.message : $t('volumeEditor.updateFailed'));
		} finally {
			saving = false;
		}
	}

	async function handleDelete(volId: string) {
		try {
			await api.deleteVolume(projectId, volId);
			toasts.success($t('volumeEditor.volumeDeleted'));
			await loadVolumes();
		} catch (e) {
			toasts.error(e instanceof Error ? e.message : $t('volumeEditor.deleteFailed'));
		}
	}

	$effect(() => {
		void projectId;
		loadVolumes();
	});
</script>

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

<div class="space-y-6">
	<!-- Header -->
	<div>
		<div class="flex items-center gap-1.5 text-sm text-[var(--text-tertiary)]">
			<a href="/projects/{projectId}" class="hover:text-[var(--text-link)] transition-colors">{$t('common.project')}</a>
			<IconChevronRight size={14} />
		</div>
		<h1 class="mt-1 text-2xl font-bold text-[var(--text-primary)]">{$t('volumeEditor.title')}</h1>
		<p class="mt-1 text-sm text-[var(--text-secondary)]">
			{$t('volumeEditor.description')}
			<strong>{$t('volumeEditor.shared')}</strong> — {$t('volumeEditor.sharedDesc')}
			<strong>{$t('volumeEditor.isolated')}</strong> — {$t('volumeEditor.isolatedDesc')}
		</p>
	</div>

	{#if loading}
		<div class="space-y-4">
			<Skeleton height="12rem" />
		</div>
	{:else if error}
		<div class="rounded-xl border border-[var(--color-danger-light)] bg-[var(--color-danger-light)] p-4">
			<p class="text-sm text-[var(--color-danger)]">{error}</p>
			<button type="button" class="mt-2 text-sm font-medium text-[var(--color-danger)] underline hover:no-underline" onclick={loadVolumes}>
				{$t('common.retry')}
			</button>
		</div>
	{:else}
		<div class="overflow-hidden rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] shadow-[var(--shadow-sm)]">
			<table class="min-w-full divide-y divide-[var(--border-primary)]">
				<thead class="bg-[var(--surface-card-hover)]">
					<tr>
						<th class="px-4 py-3 text-left text-xs font-medium text-[var(--text-tertiary)] uppercase">{$t('volumeEditor.sourceHost')}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-[var(--text-tertiary)] uppercase">{$t('volumeEditor.targetContainer')}</th>
						<th class="px-4 py-3 text-left text-xs font-medium text-[var(--text-tertiary)] uppercase">{$t('volumeEditor.mode')}</th>
						<th class="px-4 py-3 text-right text-xs font-medium text-[var(--text-tertiary)] uppercase">{$t('volumeEditor.actions')}</th>
					</tr>
				</thead>
				<tbody class="divide-y divide-[var(--border-secondary)]">
					{#each volumes as vol (vol.id)}
						{#if editingId === vol.id}
							<tr class="bg-[var(--color-brand-50)]/30">
								<td class="px-4 py-2.5">
									<input type="text" bind:value={editSource} class="block w-full rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-2 py-1 font-mono text-sm focus:border-[var(--color-brand-500)] focus:ring-1 focus:ring-[var(--color-brand-500)] focus:outline-none" />
								</td>
								<td class="px-4 py-2.5">
									<input type="text" bind:value={editTarget} class="block w-full rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-2 py-1 font-mono text-sm focus:border-[var(--color-brand-500)] focus:ring-1 focus:ring-[var(--color-brand-500)] focus:outline-none" />
								</td>
								<td class="px-4 py-2.5">
									<select bind:value={editMode} class="rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-2 py-1 text-sm focus:border-[var(--color-brand-500)] focus:ring-1 focus:ring-[var(--color-brand-500)] focus:outline-none">
										<option value="shared">{$t('volumeEditor.shared')}</option>
										<option value="isolated">{$t('volumeEditor.isolated')}</option>
									</select>
								</td>
								<td class="px-4 py-2.5 text-right">
									<div class="flex items-center justify-end gap-1">
										<button type="button" class="rounded-lg p-1.5 text-emerald-600 hover:bg-emerald-50 transition-colors" disabled={saving} onclick={handleUpdate}><IconCheck size={16} /></button>
										<button type="button" class="rounded-lg p-1.5 text-[var(--text-tertiary)] hover:bg-[var(--surface-card-hover)] transition-colors" onclick={cancelEdit}><IconX size={16} /></button>
									</div>
								</td>
							</tr>
						{:else}
							<tr class="hover:bg-[var(--surface-card-hover)] transition-colors">
								<td class="px-4 py-2.5 font-mono text-sm text-[var(--text-primary)]">{vol.source}</td>
								<td class="px-4 py-2.5 font-mono text-sm text-[var(--text-secondary)]">{vol.target}</td>
								<td class="px-4 py-2.5">
									{#if vol.mode === 'shared'}
										<span class="rounded-full bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700">{$t('volumeEditor.shared')}</span>
									{:else}
										<span class="rounded-full bg-amber-50 px-2 py-0.5 text-xs font-medium text-amber-700">{$t('volumeEditor.isolated')}</span>
									{/if}
								</td>
								<td class="whitespace-nowrap px-4 py-2.5 text-right">
									<div class="flex items-center justify-end gap-1">
										<button type="button" class="rounded-lg p-1.5 text-[var(--text-tertiary)] hover:bg-[var(--surface-card-hover)] hover:text-[var(--text-link)] transition-colors" onclick={() => startEdit(vol)}><IconEdit size={16} /></button>
										<button type="button" class="rounded-lg p-1.5 text-[var(--text-tertiary)] hover:bg-red-50 hover:text-red-600 transition-colors" onclick={() => handleDelete(vol.id)}><IconTrash size={16} /></button>
									</div>
								</td>
							</tr>
						{/if}
					{/each}

					<!-- Add new row -->
					<tr class="bg-[var(--surface-card-hover)]">
						<td class="px-4 py-2.5">
							<input type="text" bind:value={newSource} placeholder="/data/my-app/uploads" class="block w-full rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-2 py-1 font-mono text-sm focus:border-[var(--color-brand-500)] focus:ring-1 focus:ring-[var(--color-brand-500)] focus:outline-none" />
						</td>
						<td class="px-4 py-2.5">
							<input type="text" bind:value={newTarget} placeholder="/app/uploads" class="block w-full rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-2 py-1 font-mono text-sm focus:border-[var(--color-brand-500)] focus:ring-1 focus:ring-[var(--color-brand-500)] focus:outline-none" />
						</td>
						<td class="px-4 py-2.5">
							<select bind:value={newMode} class="rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-2 py-1 text-sm focus:border-[var(--color-brand-500)] focus:ring-1 focus:ring-[var(--color-brand-500)] focus:outline-none">
								<option value="shared">{$t('volumeEditor.shared')}</option>
								<option value="isolated">{$t('volumeEditor.isolated')}</option>
							</select>
						</td>
						<td class="px-4 py-2.5 text-right">
							<button
								type="button"
								class="inline-flex items-center gap-1 rounded-lg bg-[var(--color-brand-600)] px-3 py-1.5 text-xs font-medium text-white hover:bg-[var(--color-brand-700)] disabled:opacity-50 transition-colors active:animate-press"
								disabled={!newSource.trim() || !newTarget.trim() || saving}
								onclick={handleAdd}
							>
								<IconPlus size={14} />
								{saving ? $t('volumeEditor.adding') : $t('volumeEditor.add')}
							</button>
						</td>
					</tr>
				</tbody>
			</table>
		</div>

		{#if volumes.length === 0}
			<p class="text-center text-sm text-[var(--text-tertiary)]">{$t('volumeEditor.noVolumes')}</p>
		{/if}
	{/if}
</div>
