<script lang="ts">
	import { CreateAccountStore, UpdateAccountStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import type { GetAccount$result } from '$houdini';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';
	import { toGlobalId } from '$lib/utils/relay';

	type Account = NonNullable<GetAccount$result['account']>;

	interface Props {
		account?: Account;
		customers: { id: string; name: string }[];
		onSuccess?: () => void;
		onCancel?: () => void;
	}

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

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

	// Convert customerId from UUID to GlobalID to match dropdown option values
	function getCustomerGlobalId(customerId: string | null | undefined): string {
		if (!customerId) return '';
		return toGlobalId('CustomerType', customerId);
	}

	let name = $state(account?.name ?? '');
	let customerId = $state(getCustomerGlobalId(account?.customerId));
	let startDate = $state(account?.startDate ?? '');
	let endDate = $state(account?.endDate ?? '');
	let status = $state(account?.status ?? 'ACTIVE');

	const createStore = new CreateAccountStore();
	const updateStore = new UpdateAccountStore();

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

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

			if (isEdit && account) {
				const res = await updateStore.mutate({
					input: {
						id: account.id,
						name,
						customerId,
						startDate,
						endDate: endDate || null,
						status
					}
				});
				if (res.errors?.length) {
					error = res.errors.map((e) => e.message).join(', ');
					return;
				}
			} else {
				const res = await createStore.mutate({
					input: {
						name,
						customerId,
						startDate,
						endDate: endDate || null,
						status
					}
				});
				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 account';
		} finally {
			submitting = false;
		}
	}

	function handleCancel() {
		offCanvas.closeRight();
		onCancel?.();
	}
</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}>
		<div>
			<label for="name" class="mb-1.5 block text-sm font-medium text-theme">
				Account Name <span class="text-red-500">*</span>
			</label>
			<input
				id="name"
				type="text"
				bind:value={name}
				disabled={submitting}
				placeholder="Enter account 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="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}
					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>

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

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

		{#if isEdit}
			<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"
				>
					<option value="ACTIVE">Active</option>
					<option value="PENDING">Pending</option>
					<option value="INACTIVE">Inactive</option>
				</select>
			</div>
		{/if}

		<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 Account'}
				{/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>
