<script lang="ts">
	import { client } from '$lib/graphql/client';
	import {
		CREATE_CUSTOMER_PROFILE,
		type CreateCustomerProfileInput
	} from '$lib/graphql/mutations/profile';
	import type { EntityStatus } from '$lib/graphql/queries/team';

	interface Props {
		onSuccess: (profileId: string) => void;
		onCancel: () => void;
	}

	let { onSuccess, onCancel }: Props = $props();

	// Form state
	let kratosIdentityId = $state('');
	let firstName = $state('');
	let lastName = $state('');
	let email = $state('');
	let phone = $state('');
	let status = $state<EntityStatus>('ACTIVE');
	let notes = $state('');

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

	// Validate UUID format
	function isValidUuid(str: string): boolean {
		const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
		return uuidRegex.test(str);
	}

	let isValidKratosId = $derived(isValidUuid(kratosIdentityId));

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

		if (!isValidKratosId) {
			error = 'Invalid Kratos Identity ID format. Must be a valid UUID.';
			loading = false;
			return;
		}

		try {
			const input: CreateCustomerProfileInput = {
				kratosIdentityId,
				firstName,
				lastName,
				email,
				phone,
				status,
				notes
			};

			const result = await client.mutate<{ createCustomerProfile: { id: string } }>({
				mutation: CREATE_CUSTOMER_PROFILE,
				variables: { input }
			});

			const profileId = result.data?.createCustomerProfile?.id;
			if (!profileId) {
				throw new Error('Failed to create customer profile');
			}

			onSuccess(profileId);
		} catch (err) {
			error = err instanceof Error ? err.message : 'An error occurred';
		} finally {
			loading = false;
		}
	}
</script>

<form onsubmit={handleSubmit} class="space-y-5">
	{#if error}
		<div class="rounded-lg border border-error-500/30 bg-error-50/50 p-3 dark:bg-error-950/30">
			<p class="text-sm text-error-700 dark:text-error-400">{error}</p>
		</div>
	{/if}

	<div>
		<label for="kratosIdentityId" class="form-label">
			Kratos Identity ID <span class="required-indicator">*</span>
		</label>
		<input
			id="kratosIdentityId"
			type="text"
			bind:value={kratosIdentityId}
			class="input-base font-mono text-sm"
			placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
			required
			disabled={loading}
		/>
		<p class="mt-1 text-xs text-theme-muted">
			The UUID from Kratos identity. This links the profile to authentication.
		</p>
		{#if kratosIdentityId && !isValidKratosId}
			<p class="mt-1 text-xs text-error-600 dark:text-error-400">Invalid UUID format</p>
		{/if}
	</div>

	<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
		<div>
			<label for="firstName" class="form-label">
				First Name <span class="required-indicator">*</span>
			</label>
			<input
				id="firstName"
				type="text"
				bind:value={firstName}
				class="input-base"
				required
				disabled={loading}
			/>
		</div>

		<div>
			<label for="lastName" class="form-label">
				Last Name <span class="required-indicator">*</span>
			</label>
			<input
				id="lastName"
				type="text"
				bind:value={lastName}
				class="input-base"
				required
				disabled={loading}
			/>
		</div>
	</div>

	<div>
		<label for="email" class="form-label">Email</label>
		<input id="email" type="email" bind:value={email} class="input-base" disabled={loading} />
	</div>

	<div>
		<label for="phone" class="form-label">Phone</label>
		<input
			id="phone"
			type="tel"
			bind:value={phone}
			class="input-base"
			placeholder="(555) 123-4567"
			disabled={loading}
		/>
	</div>

	<div class="border-t border-theme pt-5">
		<label for="status" class="form-label">Status</label>
		<select id="status" bind:value={status} class="select-base" disabled={loading}>
			<option value="ACTIVE">Active</option>
			<option value="INACTIVE">Inactive</option>
			<option value="PENDING">Pending</option>
		</select>
	</div>

	<div class="border-t border-theme pt-5">
		<label for="notes" class="form-label">Notes</label>
		<textarea
			id="notes"
			bind:value={notes}
			class="textarea-base"
			rows="3"
			placeholder="Optional notes about this customer profile..."
			disabled={loading}
		></textarea>
	</div>

	<div class="form-actions border-t border-theme pt-5">
		<button type="button" class="btn-cancel" onclick={onCancel} disabled={loading}>Cancel</button>
		<button type="submit" class="btn-submit" disabled={loading || !isValidKratosId}>
			{#if loading}
				Creating...
			{:else}
				Create Profile
			{/if}
		</button>
	</div>
</form>
