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

	type CustomerProfile = AdminProfiles$result['customerProfiles'][number];
	type Customer = Customers$result['customers'][number];

	interface Props {
		profile?: CustomerProfile;
		customers: Customer[];
		onSuccess?: () => void;
		onCancel?: () => void;
	}

	let { profile, customers, 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 status = $state(profile?.status ?? 'ACTIVE');
	let notes = $state(profile?.notes ?? '');
	let selectedCustomerIds = $state<string[]>(profile?.customers.map((c) => c.id) ?? []);

	const createStore = new CreateCustomerProfileStore();
	const updateStore = new UpdateCustomerProfileStore();

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

	// Active customers only for selection
	let activeCustomers = $derived(customers.filter((c) => c.status === 'ACTIVE'));

	function toggleCustomer(customerId: string) {
		if (selectedCustomerIds.includes(customerId)) {
			selectedCustomerIds = selectedCustomerIds.filter((id) => id !== customerId);
		} else {
			selectedCustomerIds = [...selectedCustomerIds, customerId];
		}
	}

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

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

			if (isEdit && profile) {
				const res = await updateStore.mutate({
					input: {
						id: profile.id,
						firstName,
						lastName,
						email: email || null,
						phone: phone || null,
						status,
						notes: notes || null,
						customerIds: selectedCustomerIds.length > 0 ? selectedCustomerIds : 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,
						status,
						notes: notes || null,
						customerIds: selectedCustomerIds.length > 0 ? selectedCustomerIds : 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 customer profile';
		} 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="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>

		<!-- Customer Access -->
		<div>
			<span class="mb-1.5 block text-sm font-medium text-theme">Customer Access</span>
			<p class="mb-2 text-xs text-theme-muted">Select which customers this profile can access.</p>
			{#if activeCustomers.length > 0}
				<div
					class="max-h-48 space-y-2 overflow-y-auto rounded-lg border border-theme bg-theme-secondary p-3"
				>
					{#each activeCustomers as customer (customer.id)}
						<label class="flex cursor-pointer items-center gap-2">
							<input
								type="checkbox"
								checked={selectedCustomerIds.includes(customer.id)}
								onchange={() => toggleCustomer(customer.id)}
								disabled={submitting}
								class="h-4 w-4 rounded border-theme text-primary-500 focus:ring-primary-500"
							/>
							<span class="text-sm text-theme">{customer.name}</span>
						</label>
					{/each}
				</div>
			{:else}
				<p class="text-sm text-theme-muted italic">No active customers available.</p>
			{/if}
		</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 Customer Profile'}
				{/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>
