<script lang="ts">
	import { CreateTeamProfileStore, UpdateTeamProfileStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { fromGlobalId } from '$lib/utils/relay';
	import type { AdminProfiles$result } from '$houdini';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	type TeamProfile = AdminProfiles$result['teamProfiles'][number];

	interface Props {
		profile?: TeamProfile;
		onSuccess?: () => void;
		onCancel?: () => void;
	}

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

	let isEdit = $derived(!!profile);
	let submitting = $state(false);
	let error = $state('');

	let firstName = $state(profile?.firstName ?? '');
	let lastName = $state(profile?.lastName ?? '');
	let email = $state(profile?.email ?? '');
	let phone = $state(profile?.phone ?? '');
	let role = $state(profile?.role ?? 'TEAM_MEMBER');
	let status = $state(profile?.status ?? 'ACTIVE');
	let notes = $state(profile?.notes ?? '');

	const createStore = new CreateTeamProfileStore();
	const updateStore = new UpdateTeamProfileStore();

	const roleOptions = [
		{ value: 'ADMIN', label: 'Admin' },
		{ value: 'TEAM_LEADER', label: 'Team Leader' },
		{ value: 'TEAM_MEMBER', label: 'Team Member' }
	];

	const statusOptions = [
		{ value: 'ACTIVE', label: 'Active' },
		{ value: 'PENDING', label: 'Pending' },
		{ value: 'INACTIVE', label: 'Inactive' }
	];

	async function handleSubmit(e: SubmitEvent) {
		e.preventDefault();
		submitting = true;
		error = '';

		try {
			if (!firstName || !lastName || !role) {
				error = 'Please provide first name, last name, and role';
				return;
			}

			if (isEdit && profile) {
				const res = await updateStore.mutate({
					input: {
						id: profile.id,
						firstName,
						lastName,
						email: email || null,
						phone: phone || null,
						role,
						status,
						notes: notes || null
					}
				});
				if (res.errors?.length) {
					error = res.errors.map((e: { message: string }) => e.message).join(', ');
					return;
				}
			} else {
				const res = await createStore.mutate({
					input: {
						firstName,
						lastName,
						email: email || null,
						phone: phone || null,
						role,
						status,
						notes: notes || null
					}
				});
				if (res.errors?.length) {
					error = res.errors.map((e: { message: string }) => e.message).join(', ');
					return;
				}
			}

			offCanvas.closeRight();
			onSuccess?.();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to save team member';
		} finally {
			submitting = false;
		}
	}

	function handleCancel() {
		offCanvas.closeRight();
		onCancel?.();
	}
</script>

<div class="space-y-6">
	{#if error}
		<div class="alert-error">
			{error}
		</div>
	{/if}

	<form class="space-y-4" onsubmit={handleSubmit}>
		{#if isEdit && profile}
			<div>
				<span class="mb-1.5 block text-sm font-medium text-theme">Profile ID</span>
				<p class="font-mono text-sm text-theme-muted">{fromGlobalId(profile.id)}</p>
			</div>
		{/if}

		<div class="grid grid-cols-2 gap-4">
			<div>
				<label for="firstName" class="mb-1.5 block text-sm font-medium text-theme">
					First Name <span class="text-red-500">*</span>
				</label>
				<input
					id="firstName"
					type="text"
					bind:value={firstName}
					disabled={submitting}
					placeholder="Enter first name"
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
				/>
			</div>

			<div>
				<label for="lastName" class="mb-1.5 block text-sm font-medium text-theme">
					Last Name <span class="text-red-500">*</span>
				</label>
				<input
					id="lastName"
					type="text"
					bind:value={lastName}
					disabled={submitting}
					placeholder="Enter last name"
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
				/>
			</div>
		</div>

		<div>
			<label for="email" class="mb-1.5 block text-sm font-medium text-theme"> Email </label>
			<input
				id="email"
				type="email"
				bind:value={email}
				disabled={submitting}
				placeholder="Enter email address"
				class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
			/>
		</div>

		<div>
			<label for="phone" class="mb-1.5 block text-sm font-medium text-theme"> Phone </label>
			<input
				id="phone"
				type="tel"
				bind:value={phone}
				disabled={submitting}
				placeholder="Enter phone number"
				class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
			/>
		</div>

		<div>
			<label for="role" class="mb-1.5 block text-sm font-medium text-theme">
				Role <span class="text-red-500">*</span>
			</label>
			<select
				id="role"
				bind:value={role}
				disabled={submitting}
				class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
			>
				{#each roleOptions as option (option.value)}
					<option value={option.value}>{option.label}</option>
				{/each}
			</select>
		</div>

		<div>
			<label for="status" class="mb-1.5 block text-sm font-medium text-theme"> Status </label>
			<select
				id="status"
				bind:value={status}
				disabled={submitting}
				class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
			>
				{#each statusOptions as option (option.value)}
					<option value={option.value}>{option.label}</option>
				{/each}
			</select>
		</div>

		<div>
			<label for="notes" class="mb-1.5 block text-sm font-medium text-theme"> Notes </label>
			<textarea
				id="notes"
				bind:value={notes}
				disabled={submitting}
				rows="3"
				placeholder="Additional notes (optional)"
				class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
			></textarea>
		</div>

		<div class="flex items-center gap-3 pt-4">
			<button
				type="submit"
				disabled={submitting}
				class="flex-1 rounded-lg bg-primary-500 px-4 py-2 font-medium text-white transition-colors hover:bg-primary-600 disabled:cursor-not-allowed disabled:opacity-50"
			>
				{#if submitting}
					<span class="flex items-center justify-center gap-2">
						<IconSpinner class="h-4 w-4" />
						<span>{isEdit ? 'Saving...' : 'Creating...'}</span>
					</span>
				{:else}
					{isEdit ? 'Save Changes' : 'Create Team Member'}
				{/if}
			</button>
			<button
				type="button"
				onclick={handleCancel}
				disabled={submitting}
				class="rounded-lg border border-theme bg-theme px-4 py-2 font-medium text-theme transition-colors hover:bg-black/5 disabled:cursor-not-allowed disabled:opacity-50 dark:hover:bg-white/10"
			>
				Cancel
			</button>
		</div>
	</form>
</div>
