<script lang="ts">
	import { CreateProjectStore, UpdateProjectStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { fromGlobalId } from '$lib/utils/relay';
	import type { GetProject$result, Customers$result, Accounts$result, Team$result } from '$houdini';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	type Project = NonNullable<GetProject$result['project']>;
	type Customer = Customers$result['customers'][number];
	type Account = Accounts$result['accounts'][number];
	type TeamProfile = Team$result['teamProfiles'][number];

	interface WaveProduct {
		id: string;
		name: string;
		description: string | null;
		unitPrice: number | string;
		isArchived: boolean;
	}

	interface Props {
		project?: Project;
		customers: Customer[];
		accounts: Account[];
		teamProfiles: TeamProfile[];
		waveProducts?: WaveProduct[];
		onSuccess?: () => void;
		onCancel?: () => void;
	}

	let {
		project,
		customers,
		accounts,
		teamProfiles,
		waveProducts = [],
		onSuccess,
		onCancel
	}: Props = $props();

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

	// Helper to find customer Relay Global ID from UUID
	function findCustomerGlobalId(customerUuid: string | null | undefined): string {
		if (!customerUuid) return '';
		// Find customer whose Global ID decodes to this UUID
		const customer = customers.find((c) => fromGlobalId(c.id) === customerUuid);
		return customer?.id ?? '';
	}

	// Helper to find address Relay Global ID from UUID
	function findAddressGlobalId(addressUuid: string | null | undefined): string {
		if (!addressUuid) return '';
		// Search through all accounts for this address UUID
		for (const account of accounts) {
			const address = account.addresses?.find((a) => fromGlobalId(a.id) === addressUuid);
			if (address) return address.id;
		}
		return '';
	}

	// Helper to find account that contains an address UUID
	function findAccountForAddressUuid(addressUuid: string | null | undefined): string {
		if (!addressUuid) return '';
		for (const account of accounts) {
			const hasAddress = account.addresses?.some((a) => fromGlobalId(a.id) === addressUuid);
			if (hasAddress) return account.id;
		}
		return '';
	}

	// Helper to convert team member UUIDs (pk) to Relay Global IDs
	function findTeamMemberGlobalIds(memberPks: { pk: string }[] | null | undefined): string[] {
		if (!memberPks) return [];
		return memberPks
			.map((m) => {
				// Find team profile whose Global ID decodes to this pk UUID
				const profile = teamProfiles.find((p) => fromGlobalId(p.id) === m.pk);
				return profile?.id;
			})
			.filter((id): id is string => !!id);
	}

	// Form fields - convert project UUIDs to Relay Global IDs for form
	let customerId = $state(findCustomerGlobalId(project?.customerId));
	let selectedAccountId = $state(findAccountForAddressUuid(project?.accountAddressId));
	let accountAddressId = $state(findAddressGlobalId(project?.accountAddressId));
	let useManualAddress = $state(
		!project?.accountAddressId && !!(project?.streetAddress || project?.city)
	);
	let name = $state(project?.name ?? '');
	let date = $state(project?.date ?? '');
	let amount = $state(project?.amount?.toString() ?? '');
	let labor = $state(project?.labor?.toString() ?? '');
	let status = $state(project?.status ?? 'SCHEDULED');
	let streetAddress = $state(project?.streetAddress ?? '');
	let city = $state(project?.city ?? '');
	let stateCode = $state(project?.state ?? '');
	let zipCode = $state(project?.zipCode ?? '');
	let notes = $state(project?.notes ?? '');
	let selectedTeamMemberIds = $state<string[]>(findTeamMemberGlobalIds(project?.teamMembers));
	let waveServiceId = $state(project?.waveServiceId ?? '');

	// Find linked Wave product for display
	let linkedProduct = $derived(
		waveServiceId ? waveProducts.find((p) => fromGlobalId(p.id) === waveServiceId) : null
	);

	// Filter accounts for selected customer
	// customerId state is now a Relay Global ID
	// account.customerId is a UUID, so we need to convert for comparison
	let customerAccounts = $derived(() => {
		if (!customerId) return [];
		const customerUuid = fromGlobalId(customerId);
		return accounts.filter((a) => a.customerId === customerUuid);
	});

	// Get addresses for selected account
	let accountAddresses = $derived(() => {
		if (!selectedAccountId) return [];
		const account = customerAccounts().find((a) => a.id === selectedAccountId);
		return account?.addresses ?? [];
	});

	// Get currently selected address details for display
	let selectedAddressDetails = $derived(() => {
		if (!accountAddressId) return null;
		for (const account of customerAccounts()) {
			const address = account.addresses?.find((a) => a.id === accountAddressId);
			if (address) {
				return { account, address };
			}
		}
		return null;
	});

	// When customer changes, reset account and address
	function handleCustomerChange() {
		selectedAccountId = '';
		accountAddressId = '';
		useManualAddress = false;
	}

	// When account changes, auto-select if only one address, otherwise reset
	function handleAccountChange() {
		const addresses = accountAddresses();
		if (addresses.length === 1) {
			accountAddressId = addresses[0].id;
		} else {
			accountAddressId = '';
		}
		useManualAddress = false;
	}

	// Toggle manual address mode
	function toggleManualAddress() {
		useManualAddress = !useManualAddress;
		if (useManualAddress) {
			selectedAccountId = '';
			accountAddressId = '';
		}
	}

	// Non-admin team members only
	let nonAdminTeamMembers = $derived(teamProfiles.filter((p) => p.role !== 'ADMIN'));

	// Get admin profile ID
	let adminProfileId = $derived(teamProfiles.find((p) => p.role === 'ADMIN')?.id ?? null);

	// Track if project is dispatched (admin profile is in team members)
	let isDispatched = $derived(
		adminProfileId ? selectedTeamMemberIds.includes(adminProfileId) : false
	);

	function toggleDispatched() {
		if (!adminProfileId) return;
		if (isDispatched) {
			// When un-dispatching, remove admin and clear all team members
			selectedTeamMemberIds = [];
		} else {
			selectedTeamMemberIds = [...selectedTeamMemberIds, adminProfileId];
		}
	}

	const createStore = new CreateProjectStore();
	const updateStore = new UpdateProjectStore();

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

		try {
			if (!customerId || !name || !date || !amount) {
				error = 'Please provide customer, name, date, and amount';
				return;
			}

			// Require either accountAddressId OR manual address
			const hasAccountAddress = !!accountAddressId;
			const hasManualAddress = !!(streetAddress && city && stateCode);
			if (!hasAccountAddress && !hasManualAddress) {
				error = 'Please select an account address or enter a manual address';
				return;
			}

			const baseInput = {
				customerId,
				accountAddressId: accountAddressId || null,
				name,
				date,
				amount: parseFloat(amount),
				labor: labor ? parseFloat(labor) : 0,
				status,
				streetAddress: accountAddressId ? null : streetAddress || null,
				city: accountAddressId ? null : city || null,
				state: accountAddressId ? null : stateCode || null,
				zipCode: accountAddressId ? null : zipCode || null,
				notes: notes || null,
				teamMemberIds: selectedTeamMemberIds.length > 0 ? selectedTeamMemberIds : null,
				waveServiceId: waveServiceId || ''
			};

			if (isEdit && project) {
				const res = await updateStore.mutate({
					input: {
						id: project.id,
						...baseInput
					}
				});
				if (res.errors?.length) {
					error = res.errors.map((e) => e.message).join(', ');
					return;
				}
			} else {
				const res = await createStore.mutate({
					input: baseInput
				});
				if (res.errors?.length) {
					error = res.errors.map((e) => e.message).join(', ');
					return;
				}
			}

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

	function handleCancel() {
		offCanvas.closeRight();
		onCancel?.();
	}

	function toggleTeamMember(id: string) {
		if (selectedTeamMemberIds.includes(id)) {
			selectedTeamMemberIds = selectedTeamMemberIds.filter((m) => m !== id);
		} else {
			selectedTeamMemberIds = [...selectedTeamMemberIds, id];
		}
	}
</script>

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

	<form class="space-y-4" onsubmit={handleSubmit}>
		<!-- Customer -->
		<div>
			<label for="customerId" class="mb-1.5 block text-sm font-medium text-theme">
				Customer <span class="text-red-500">*</span>
			</label>
			<div class="relative w-full">
				<select
					id="customerId"
					bind:value={customerId}
					onchange={handleCustomerChange}
					disabled={submitting}
					class="w-full appearance-none rounded-lg border border-theme bg-theme py-2 pr-10 pl-3 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
				>
					<option value="">Select a customer</option>
					{#each customers as customer (customer.id)}
						<option value={customer.id}>{customer.name}</option>
					{/each}
				</select>
				<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
					<svg
						class="h-4 w-4 text-theme-muted"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M19 9l-7 7-7-7"
						/>
					</svg>
				</div>
			</div>
		</div>

		<!-- Address Selection Section -->
		{#if customerId}
			<div class="space-y-4 rounded-lg border border-theme bg-theme-card p-4">
				<div class="flex items-center justify-between">
					<p class="text-sm font-medium text-theme">Project Location</p>
					{#if customerAccounts().length > 0}
						<button
							type="button"
							onclick={toggleManualAddress}
							class="text-xs text-primary-500 hover:text-primary-600"
						>
							{useManualAddress ? 'Use account address' : 'Enter address manually'}
						</button>
					{/if}
				</div>

				{#if !useManualAddress && customerAccounts().length > 0}
					<!-- Account Selection -->
					<div>
						<label for="selectedAccountId" class="mb-1.5 block text-sm text-theme-secondary">
							Account
						</label>
						<div class="relative w-full">
							<select
								id="selectedAccountId"
								bind:value={selectedAccountId}
								onchange={handleAccountChange}
								disabled={submitting}
								class="w-full appearance-none rounded-lg border border-theme bg-theme py-2 pr-10 pl-3 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
							>
								<option value="">Select an account</option>
								{#each customerAccounts() as account (account.id)}
									<option value={account.id}>{account.name}</option>
								{/each}
							</select>
							<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
								<svg
									class="h-4 w-4 text-theme-muted"
									style="fill: none"
									stroke="currentColor"
									viewBox="0 0 24 24"
								>
									<path
										stroke-linecap="round"
										stroke-linejoin="round"
										stroke-width="2"
										d="M19 9l-7 7-7-7"
									/>
								</svg>
							</div>
						</div>
					</div>

					<!-- Address Selection (shown when account is selected) -->
					{#if selectedAccountId && accountAddresses().length > 0}
						<div>
							<label for="accountAddressId" class="mb-1.5 block text-sm text-theme-secondary">
								Address
							</label>
							{#if accountAddresses().length === 1}
								<!-- Single address - show as confirmation -->
								{@const address = accountAddresses()[0]}
								<div
									class="rounded-lg border border-primary-200 bg-primary-50 p-3 dark:border-primary-800 dark:bg-primary-900/20"
								>
									<div class="flex items-start gap-2">
										<svg
											class="mt-0.5 h-4 w-4 flex-shrink-0 text-primary-500"
											style="fill: none"
											stroke="currentColor"
											viewBox="0 0 24 24"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
											/>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
											/>
										</svg>
										<div class="text-sm">
											<p class="font-medium text-theme">{address.streetAddress}</p>
											<p class="text-theme-secondary">
												{address.city}, {address.state}
												{address.zipCode}
											</p>
										</div>
									</div>
								</div>
							{:else}
								<!-- Multiple addresses - show dropdown -->
								<div class="relative w-full">
									<select
										id="accountAddressId"
										bind:value={accountAddressId}
										disabled={submitting}
										class="w-full appearance-none rounded-lg border border-theme bg-theme py-2 pr-10 pl-3 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
									>
										<option value="">Select an address</option>
										{#each accountAddresses() as address (address.id)}
											<option value={address.id}>
												{address.streetAddress}, {address.city}, {address.state}
											</option>
										{/each}
									</select>
									<div
										class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3"
									>
										<svg
											class="h-4 w-4 text-theme-muted"
											style="fill: none"
											stroke="currentColor"
											viewBox="0 0 24 24"
										>
											<path
												stroke-linecap="round"
												stroke-linejoin="round"
												stroke-width="2"
												d="M19 9l-7 7-7-7"
											/>
										</svg>
									</div>
								</div>
							{/if}
						</div>

						<!-- Show selected address confirmation (for multi-address accounts) -->
						{#if accountAddresses().length > 1 && selectedAddressDetails()}
							{@const details = selectedAddressDetails()}
							<div
								class="rounded-lg border border-primary-200 bg-primary-50 p-3 dark:border-primary-800 dark:bg-primary-900/20"
							>
								<div class="flex items-start gap-2">
									<svg
										class="mt-0.5 h-4 w-4 flex-shrink-0 text-primary-500"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
										/>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
										/>
									</svg>
									<div class="text-sm">
										<p class="font-medium text-theme">{details?.address.streetAddress}</p>
										<p class="text-theme-secondary">
											{details?.address.city}, {details?.address.state}
											{details?.address.zipCode}
										</p>
									</div>
								</div>
							</div>
						{/if}
					{:else if selectedAccountId && accountAddresses().length === 0}
						<p class="text-sm text-theme-muted italic">
							This account has no addresses. Please enter address manually.
						</p>
					{/if}
				{:else}
					<!-- Manual Address Entry -->
					<div class="space-y-3">
						<div>
							<label for="streetAddress" class="mb-1 block text-sm text-theme-secondary"
								>Street</label
							>
							<input
								id="streetAddress"
								type="text"
								bind:value={streetAddress}
								disabled={submitting}
								placeholder="123 Main St"
								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 class="grid grid-cols-6 gap-3">
							<div class="col-span-3">
								<label for="city" class="mb-1 block text-sm text-theme-secondary">City</label>
								<input
									id="city"
									type="text"
									bind:value={city}
									disabled={submitting}
									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 class="col-span-1">
								<label for="stateCode" class="mb-1 block text-sm text-theme-secondary">State</label>
								<input
									id="stateCode"
									type="text"
									bind:value={stateCode}
									disabled={submitting}
									maxlength="2"
									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 class="col-span-2">
								<label for="zipCode" class="mb-1 block text-sm text-theme-secondary">Zip</label>
								<input
									id="zipCode"
									type="text"
									bind:value={zipCode}
									disabled={submitting}
									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>
				{/if}
			</div>
		{/if}

		<!-- Project Name -->
		<div>
			<label for="name" class="mb-1.5 block text-sm font-medium text-theme">
				Project Name <span class="text-red-500">*</span>
			</label>
			<input
				id="name"
				type="text"
				bind:value={name}
				disabled={submitting}
				placeholder="e.g., Deep Clean - March"
				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>

		<!-- Date -->
		<div>
			<label for="date" class="mb-1.5 block text-sm font-medium text-theme">
				Date <span class="text-red-500">*</span>
			</label>
			<input
				id="date"
				type="date"
				bind:value={date}
				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"
			/>
		</div>

		<!-- Amount + Labor -->
		<div class="grid grid-cols-2 gap-4">
			<div>
				<label for="amount" class="mb-1.5 block text-sm font-medium text-theme">
					Amount <span class="text-red-500">*</span>
				</label>
				<div class="relative">
					<span class="absolute top-1/2 left-3 -translate-y-1/2 text-theme-muted">$</span>
					<input
						id="amount"
						type="number"
						step="0.01"
						min="0"
						bind:value={amount}
						disabled={submitting}
						placeholder="0.00"
						class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme py-2 pr-3 pl-7 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="labor" class="mb-1.5 block text-sm font-medium text-theme"> Labor </label>
				<div class="relative">
					<span class="absolute top-1/2 left-3 -translate-y-1/2 text-theme-muted">$</span>
					<input
						id="labor"
						type="number"
						step="0.01"
						min="0"
						bind:value={labor}
						disabled={submitting}
						placeholder="0.00"
						class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme py-2 pr-3 pl-7 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
					/>
				</div>
			</div>
		</div>

		<!-- Status (only for edit) -->
		{#if isEdit}
			<div>
				<label for="status" class="mb-1.5 block text-sm font-medium text-theme"> Status </label>
				<div class="relative w-full">
					<select
						id="status"
						bind:value={status}
						disabled={submitting}
						class="w-full appearance-none rounded-lg border border-theme bg-theme py-2 pr-10 pl-3 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
					>
						<option value="SCHEDULED">Scheduled</option>
						<option value="IN_PROGRESS">In Progress</option>
						<option value="COMPLETED">Completed</option>
					</select>
					<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
						<svg
							class="h-4 w-4 text-theme-muted"
							style="fill: none"
							stroke="currentColor"
							viewBox="0 0 24 24"
						>
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M19 9l-7 7-7-7"
							/>
						</svg>
					</div>
				</div>
			</div>
		{/if}

		<!-- Dispatched Toggle -->
		<div class="flex items-center justify-between rounded-lg border border-theme bg-theme-card p-3">
			<div>
				<p class="text-sm font-medium text-theme">Dispatched</p>
				<p class="text-xs text-theme-muted">Required before assigning team members</p>
			</div>
			<button
				type="button"
				onclick={toggleDispatched}
				disabled={submitting}
				class="relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 {isDispatched
					? 'bg-emerald-500'
					: 'bg-gray-200 dark:bg-gray-700'}"
				role="switch"
				aria-checked={isDispatched}
				aria-label="Toggle dispatched status"
			>
				<span
					class="pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out {isDispatched
						? 'translate-x-5'
						: 'translate-x-0'}"
				></span>
			</button>
		</div>

		<!-- Team Members -->
		<div>
			<p class="mb-1.5 text-sm font-medium text-theme">Team Members</p>
			<div
				class="space-y-2 rounded-lg border border-theme bg-theme-card p-3 {!isDispatched
					? 'opacity-50'
					: ''}"
			>
				{#if !isDispatched}
					<p class="text-sm text-theme-muted italic">Enable "Dispatched" to assign team members</p>
				{:else if nonAdminTeamMembers.length > 0}
					{#each nonAdminTeamMembers as member (member.id)}
						<label class="flex cursor-pointer items-center gap-3 rounded-lg interactive p-2">
							<input
								type="checkbox"
								checked={selectedTeamMemberIds.includes(member.id)}
								onchange={() => toggleTeamMember(member.id)}
								disabled={submitting}
								class="h-4 w-4 rounded border-input text-primary-500 focus:ring-primary-500"
							/>
							<span class="text-sm text-theme">{member.fullName}</span>
							{#if member.role === 'TEAM_LEADER'}
								<span
									class="rounded bg-primary-100 px-1.5 py-0.5 text-xs text-primary-700 dark:bg-primary-900/40 dark:text-primary-400"
								>
									TL
								</span>
							{/if}
						</label>
					{/each}
				{:else}
					<p class="text-sm text-theme-muted">No team members available</p>
				{/if}
			</div>
		</div>

		<!-- Notes -->
		<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="Optional notes about the project"
				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>

		<!-- Wave Product -->
		{#if waveProducts.length > 0}
			<div class="border-t border-theme pt-4">
				<label for="waveProduct" class="mb-1.5 block text-sm font-medium text-theme">
					Wave Product
				</label>
				<select
					id="waveProduct"
					bind:value={waveServiceId}
					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"
				>
					<option value="">No linked product</option>
					{#each waveProducts as product (product.id)}
						{@const decodedId = fromGlobalId(product.id)}
						<option value={decodedId}>
							{product.name} (${Number(product.unitPrice).toFixed(2)})
						</option>
					{/each}
				</select>
				{#if linkedProduct}
					<p class="mt-1 text-xs text-theme-muted">
						Currently linked to: {linkedProduct.name}
					</p>
				{/if}
			</div>
		{/if}

		<!-- Submit Buttons -->
		<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 Project'}
				{/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>
