<script lang="ts">
	import { onMount } from 'svelte';
	import { t } from '$lib/i18n';
	import { IconLoader, IconPlus, IconTrash, IconUsers } from '$lib/components/icons';
	import EmptyState from '$lib/components/EmptyState.svelte';
	import FormField from '$lib/components/FormField.svelte';
	import Skeleton from '$lib/components/Skeleton.svelte';
	import {
		getAuthSettings,
		updateAuthSettings,
		listUsers as apiListUsers,
		createUser,
		deleteUser as apiDeleteUser,
		ApiError
	} from '$lib/api';

	interface AuthSettings {
		auth_mode: string;
		oidc_client_id: string;
		oidc_client_secret: string;
		oidc_issuer_url: string;
		oidc_redirect_url: string;
	}

	interface User {
		id: string;
		username: string;
		email: string;
		role: string;
		created_at: string;
	}

	let loading = $state(true);
	let settings = $state<AuthSettings>({
		auth_mode: 'local', oidc_client_id: '', oidc_client_secret: '', oidc_issuer_url: '', oidc_redirect_url: ''
	});
	let users = $state<User[]>([]);
	let saving = $state(false);
	let message = $state('');
	let error = $state('');

	let newUsername = $state('');
	let newPassword = $state('');
	let newEmail = $state('');
	let newRole = $state('viewer');

	onMount(async () => {
		try {
			await Promise.all([loadSettings(), loadUsers()]);
		} finally {
			loading = false;
		}
	});

	async function loadSettings() {
		try {
			settings = await getAuthSettings();
		} catch (err: unknown) {
			error = err instanceof ApiError ? err.message : $t('settingsAuth.loadFailed');
		}
	}

	async function loadUsers() {
		try {
			users = (await apiListUsers()) ?? [];
		} catch (err: unknown) {
			error = err instanceof ApiError ? err.message : $t('settingsAuth.loadFailed');
		}
	}

	async function saveSettings() {
		saving = true; message = ''; error = '';
		try {
			await updateAuthSettings(settings);
			message = $t('settingsAuth.saved');
		} catch (err: unknown) {
			error = err instanceof ApiError ? err.message : $t('settingsAuth.saveFailed');
		} finally {
			saving = false;
		}
	}

	async function addUser() {
		if (!newUsername || !newPassword) { error = $t('settingsAuth.usernameRequired'); return; }
		try {
			await createUser({ username: newUsername, password: newPassword, email: newEmail, role: newRole });
			newUsername = ''; newPassword = ''; newEmail = ''; newRole = 'viewer';
			await loadUsers();
			message = $t('settingsAuth.userCreated');
		} catch (err: unknown) {
			error = err instanceof ApiError ? err.message : $t('settingsAuth.createFailed');
		}
	}

	async function handleDeleteUser(id: string) {
		if (!confirm($t('settingsAuth.deleteConfirm'))) return;
		try {
			await apiDeleteUser(id);
			await loadUsers();
			message = $t('settingsAuth.userDeleted');
		} catch (err: unknown) {
			error = err instanceof ApiError ? err.message : $t('settingsAuth.deleteFailed');
		}
	}
</script>

<div class="space-y-6">
	{#if loading}
		<div class="space-y-4">
			<Skeleton height="2rem" width="12rem" />
			<Skeleton height="6rem" />
			<Skeleton height="12rem" />
		</div>
	{:else}
	<div>
		<h2 class="text-lg font-semibold text-[var(--text-primary)]">{$t('settingsAuth.title')}</h2>
		<p class="text-sm text-[var(--text-secondary)]">{$t('settingsAuth.description')}</p>
	</div>

	{#if message}
		<div class="rounded-lg bg-emerald-50 p-3 text-sm text-emerald-700">{message}</div>
	{/if}
	{#if error}
		<div class="rounded-lg bg-[var(--color-danger-light)] p-3 text-sm text-[var(--color-danger)]">{error}</div>
	{/if}

	<!-- Auth Mode -->
	<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
		<h3 class="text-base font-semibold text-[var(--text-primary)]">{$t('settingsAuth.authMode')}</h3>
		<div class="mt-4 flex gap-4">
			<label class="flex items-center gap-2 cursor-pointer">
				<input type="radio" bind:group={settings.auth_mode} value="local" class="h-4 w-4 text-[var(--color-brand-600)] focus:ring-[var(--color-brand-500)]" />
				<span class="text-sm font-medium text-[var(--text-secondary)]">{$t('settingsAuth.local')}</span>
			</label>
			<label class="flex items-center gap-2 cursor-pointer">
				<input type="radio" bind:group={settings.auth_mode} value="oidc" class="h-4 w-4 text-[var(--color-brand-600)] focus:ring-[var(--color-brand-500)]" />
				<span class="text-sm font-medium text-[var(--text-secondary)]">{$t('settingsAuth.oidc')}</span>
			</label>
		</div>
	</div>

	<!-- OIDC Config -->
	{#if settings.auth_mode === 'oidc'}
		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)] animate-scale-in">
			<h3 class="text-base font-semibold text-[var(--text-primary)]">{$t('settingsAuth.oidcConfig')}</h3>
			<div class="mt-4 space-y-4">
				{#each [
					{ id: 'issuer', label: $t('settingsAuth.issuerUrl'), type: 'url', key: 'oidc_issuer_url', placeholder: 'https://auth.example.com/application/o/docker-watcher/' },
					{ id: 'client_id', label: $t('settingsAuth.clientId'), type: 'text', key: 'oidc_client_id', placeholder: '' },
					{ id: 'client_secret', label: $t('settingsAuth.clientSecret'), type: 'password', key: 'oidc_client_secret', placeholder: '' },
					{ id: 'redirect', label: $t('settingsAuth.redirectUrl'), type: 'url', key: 'oidc_redirect_url', placeholder: 'https://watcher.example.com/api/auth/oidc/callback' }
				] as field}
					<div class="flex flex-col gap-1.5">
						<label for={field.id} class="text-sm font-medium text-[var(--text-primary)]">{field.label}</label>
						<input
							id={field.id}
							type={field.type}
							bind:value={settings[field.key as keyof AuthSettings]}
							placeholder={field.placeholder}
							class="w-full rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-3 py-2 text-sm text-[var(--text-primary)] placeholder:text-[var(--text-tertiary)] focus:border-[var(--color-brand-500)] focus:outline-none focus:ring-2 focus:ring-[var(--color-brand-500)]"
						/>
					</div>
				{/each}
			</div>
		</div>
	{/if}

	<button onclick={saveSettings} disabled={saving} class="inline-flex items-center gap-2 rounded-lg bg-[var(--color-brand-600)] px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-[var(--color-brand-700)] disabled:opacity-50 transition-colors active:animate-press">
		{#if saving}<IconLoader size={16} />{/if}
		{saving ? $t('settingsAuth.saving') : $t('settingsAuth.saveSettings')}
	</button>

	<!-- Local Users -->
	<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
		<h3 class="text-base font-semibold text-[var(--text-primary)]">{$t('settingsAuth.localUsers')}</h3>

		{#if users.length > 0}
			<div class="mt-4 overflow-hidden rounded-xl border border-[var(--border-primary)]">
				<table class="min-w-full divide-y divide-[var(--border-primary)]">
					<thead class="bg-[var(--surface-card-hover)]">
						<tr>
							<th class="px-4 py-2.5 text-left text-xs font-medium uppercase text-[var(--text-tertiary)]">{$t('settingsAuth.username')}</th>
							<th class="px-4 py-2.5 text-left text-xs font-medium uppercase text-[var(--text-tertiary)]">{$t('settingsAuth.email')}</th>
							<th class="px-4 py-2.5 text-left text-xs font-medium uppercase text-[var(--text-tertiary)]">{$t('settingsAuth.role')}</th>
							<th class="px-4 py-2.5 text-left text-xs font-medium uppercase text-[var(--text-tertiary)]">{$t('settingsAuth.created')}</th>
							<th class="px-4 py-2.5"></th>
						</tr>
					</thead>
					<tbody class="divide-y divide-[var(--border-secondary)]">
						{#each users as user}
							<tr class="hover:bg-[var(--surface-card-hover)] transition-colors">
								<td class="px-4 py-2.5 text-sm text-[var(--text-primary)]">{user.username}</td>
								<td class="px-4 py-2.5 text-sm text-[var(--text-secondary)]">{user.email || '-'}</td>
								<td class="px-4 py-2.5">
									<span class="inline-flex rounded-full px-2 py-0.5 text-xs font-semibold {user.role === 'admin' ? 'bg-purple-50 text-purple-700' : 'bg-gray-100 text-gray-700'}">
										{user.role}
									</span>
								</td>
								<td class="px-4 py-2.5 text-sm text-[var(--text-secondary)]">{user.created_at}</td>
								<td class="px-4 py-2.5 text-right">
									<button onclick={() => handleDeleteUser(user.id)} class="rounded-lg p-1.5 text-[var(--text-tertiary)] hover:bg-red-50 hover:text-red-600 transition-colors" title={$t('common.delete')} aria-label={$t('common.delete')}>
										<IconTrash size={16} />
									</button>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		{:else}
			<div class="mt-4">
				<EmptyState title={$t('empty.noUsers')} description={$t('empty.noUsersDesc')} icon="users" />
			</div>
		{/if}

		<div class="mt-6 border-t border-[var(--border-primary)] pt-4">
			<h4 class="text-sm font-semibold text-[var(--text-primary)]">{$t('settingsAuth.addUser')}</h4>
			<div class="mt-3 grid grid-cols-2 gap-3">
				<FormField label={$t('settingsAuth.username')} name="newUsername" bind:value={newUsername} placeholder={$t('settingsAuth.username')} required />
				<FormField label={$t('settingsAuth.password')} name="newPassword" type="password" bind:value={newPassword} placeholder={$t('settingsAuth.password')} required />
				<FormField label={$t('settingsAuth.email')} name="newEmail" type="email" bind:value={newEmail} placeholder={$t('settingsAuth.email')} />
				<div>
					<label for="newRole" class="block text-sm font-medium text-[var(--text-primary)]">{$t('settingsAuth.role')}</label>
					<select id="newRole" bind:value={newRole} class="mt-1.5 block w-full rounded-lg border border-[var(--border-input)] bg-[var(--surface-input)] px-3 py-2 text-sm text-[var(--text-primary)] focus:border-[var(--color-brand-500)] focus:outline-none focus:ring-1 focus:ring-[var(--color-brand-500)]">
						<option value="viewer">{$t('settingsAuth.viewer')}</option>
						<option value="admin">{$t('settingsAuth.admin')}</option>
					</select>
				</div>
			</div>
			<button onclick={addUser} class="mt-3 inline-flex items-center gap-2 rounded-lg bg-[var(--color-brand-600)] px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-[var(--color-brand-700)] transition-colors active:animate-press">
				<IconPlus size={16} />
				{$t('settingsAuth.addUser')}
			</button>
		</div>
	</div>
	{/if}
</div>
