<script lang="ts">
	import { client } from '$lib/graphql/client';
	import { CREATE_TEAM_PROFILE, type CreateTeamProfileInput } from '$lib/graphql/mutations/profile';
	import type { TeamRole, 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 role = $state<TeamRole>('TEAM_MEMBER');
	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: CreateTeamProfileInput = {
				kratosIdentityId,
				firstName,
				lastName,
				email,
				phone,
				role,
				status,
				notes
			};

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

			const profileId = result.data?.createTeamProfile?.id;
			if (!profileId) {
				throw new Error('Failed to create team 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">
		<h3 class="mb-3 text-sm font-medium text-theme">Role & Access</h3>

		<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
			<div>
				<label for="role" class="form-label">Role <span class="required-indicator">*</span></label>
				<select id="role" bind:value={role} class="select-base" disabled={loading}>
					<option value="ADMIN">Admin</option>
					<option value="TEAM_LEADER">Team Leader</option>
					<option value="TEAM_MEMBER">Team Member</option>
				</select>
			</div>

			<div>
				<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>
	</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 team member..."
			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>
