<script lang="ts">
	import type { SettingsFlow } from '@ory/client';
	import { kratosClient } from '$lib/kratos';
	import { formDataToJson } from '$lib/utils';
	import { PUBLIC_KRATOS_URL } from '$env/static/public';

	let { flow }: { flow: SettingsFlow } = $props();

	let loading = $state(false);
	let error = $state<string | null>(null);
	let success = $state(false);

	// Extract current values from flow
	const email = $derived(
		(flow.ui.nodes.find((n: any) => n.attributes?.name === 'traits.email')?.attributes as any)
			?.value || ''
	);
	const firstName = $derived(
		(flow.ui.nodes.find((n: any) => n.attributes?.name === 'traits.name.first')?.attributes as any)
			?.value || ''
	);
	const lastName = $derived(
		(flow.ui.nodes.find((n: any) => n.attributes?.name === 'traits.name.last')?.attributes as any)
			?.value || ''
	);
	const phone = $derived(
		(flow.ui.nodes.find((n: any) => n.attributes?.name === 'traits.phone')?.attributes as any)
			?.value || ''
	);
	const csrfToken = $derived(
		(flow.ui.nodes.find((n: any) => n.attributes?.name === 'csrf_token')?.attributes as any)
			?.value || ''
	);

	async function handleSubmit(event: SubmitEvent) {
		event.preventDefault();
		loading = true;
		error = null;
		success = false;

		const form = event.target as HTMLFormElement;
		const formData = new FormData(form);

		// Add the method field (required by Kratos)
		formData.set('method', 'profile');

		// Convert to JSON
		const updateBody = formDataToJson(formData);

		try {
			await kratosClient.updateSettingsFlow({
				flow: flow.id,
				updateSettingsFlowBody: updateBody as any
			});

			success = true;
			// Reload to show updated info
			setTimeout(() => {
				window.location.href = window.location.pathname + '?updated=true';
			}, 1000);
		} catch (err: any) {
			console.error('Settings update failed:', err);

			if (err.response?.status === 410) {
				window.location.href = `${PUBLIC_KRATOS_URL}/self-service/settings/browser`;
			} else if (err.response?.data?.ui) {
				error = 'Validation failed. Please check your input.';
			} else {
				error = 'Failed to update settings. Please try again.';
			}
		} finally {
			loading = false;
		}
	}
</script>

<form onsubmit={handleSubmit} class="space-y-4">
	<!-- CSRF Token -->
	<input type="hidden" name="csrf_token" value={csrfToken} />

	{#if error}
		<div class="alert-error">
			<p>{error}</p>
		</div>
	{/if}

	{#if success}
		<div class="alert-success">
			<p>Profile updated successfully!</p>
		</div>
	{/if}

	<!-- Email -->
	<div>
		<label for="email" class="form-label">
			Email <span class="text-error-500">*</span>
		</label>
		<input
			type="email"
			id="email"
			name="traits.email"
			value={email}
			required
			class="input-base"
		/>
	</div>

	<!-- First Name -->
	<div>
		<label for="first-name" class="form-label">
			First Name <span class="text-error-500">*</span>
		</label>
		<input
			type="text"
			id="first-name"
			name="traits.name.first"
			value={firstName}
			required
			class="input-base"
		/>
	</div>

	<!-- Last Name -->
	<div>
		<label for="last-name" class="form-label">
			Last Name <span class="text-error-500">*</span>
		</label>
		<input
			type="text"
			id="last-name"
			name="traits.name.last"
			value={lastName}
			required
			class="input-base"
		/>
	</div>

	<!-- Phone (Optional) -->
	<div>
		<label for="phone" class="form-label">Phone Number</label>
		<input
			type="tel"
			id="phone"
			name="traits.phone"
			value={phone}
			pattern="^[0-9\s\-+()]*$"
			class="input-base"
		/>
	</div>

	<!-- Submit Button -->
	<button
		type="submit"
		disabled={loading}
		class="btn-primary w-full disabled:opacity-50"
	>
		{loading ? 'Saving...' : 'Save Changes'}
	</button>
</form>
