<script lang="ts">
	import { client } from '$lib/graphql/client';
	import {
		CREATE_CUSTOMER_ADDRESS,
		UPDATE_CUSTOMER_ADDRESS,
		type CreateCustomerAddressInput,
		type UpdateCustomerAddressInput
	} from '$lib/graphql/mutations/customer';
	import type { CustomerAddress } from '$lib/graphql/queries/customer';

	interface Props {
		address?: CustomerAddress;
		customerId: string;
		onSuccess: () => void;
		onCancel: () => void;
	}

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

	let isEdit = $derived(!!address);

	// Form state - use $effect to sync from props
	let name = $state('');
	let streetAddress = $state('');
	let city = $state('');
	let stateCode = $state('');
	let zipCode = $state('');
	let notes = $state(''); // Address notes not in query yet, but supported by backend
	let isPrimary = $state(false);
	let isActive = $state(true);

	$effect(() => {
		name = address?.name ?? '';
		streetAddress = address?.streetAddress ?? '';
		city = address?.city ?? '';
		stateCode = address?.state ?? '';
		zipCode = address?.zipCode ?? '';
		isPrimary = address?.isPrimary ?? false;
		isActive = address?.isActive ?? true;
	});

	let loading = $state(false);
	let error = $state<string | null>(null);

	async function handleSubmit(event: SubmitEvent) {
		event.preventDefault();
		loading = true;
		error = null;

		try {
			if (isEdit && address) {
				const input: UpdateCustomerAddressInput = {
					name: name || undefined,
					streetAddress: streetAddress || undefined,
					city: city || undefined,
					state: stateCode || undefined,
					zipCode: zipCode || undefined,
					notes: notes || undefined,
					isPrimary,
					isActive
				};

				await client.mutate({
					mutation: UPDATE_CUSTOMER_ADDRESS,
					variables: { id: address.id, input }
				});
			} else {
				const input: CreateCustomerAddressInput = {
					name: name || undefined,
					streetAddress,
					city,
					state: stateCode,
					zipCode,
					notes: notes || undefined,
					isPrimary
				};

				await client.mutate({
					mutation: CREATE_CUSTOMER_ADDRESS,
					variables: { customerId, input }
				});
			}

			onSuccess();
		} 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="name" class="form-label">Address Name</label>
		<input
			id="name"
			type="text"
			bind:value={name}
			class="input-base"
			placeholder="e.g., Main Office, Billing Address"
			disabled={loading}
		/>
	</div>

	<div>
		<label for="streetAddress" class="form-label">
			Street Address <span class="required-indicator">*</span>
		</label>
		<input
			id="streetAddress"
			type="text"
			bind:value={streetAddress}
			class="input-base"
			required
			disabled={loading}
		/>
	</div>

	<div>
		<label for="city" class="form-label">
			City <span class="required-indicator">*</span>
		</label>
		<input id="city" type="text" bind:value={city} class="input-base" required disabled={loading} />
	</div>

	<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
		<div>
			<label for="stateCode" class="form-label">
				State <span class="required-indicator">*</span>
			</label>
			<input
				id="stateCode"
				type="text"
				bind:value={stateCode}
				class="input-base"
				maxlength="2"
				placeholder="TX"
				required
				disabled={loading}
			/>
		</div>
		<div>
			<label for="zipCode" class="form-label">
				ZIP Code <span class="required-indicator">*</span>
			</label>
			<input
				id="zipCode"
				type="text"
				bind:value={zipCode}
				class="input-base"
				required
				disabled={loading}
			/>
		</div>
	</div>

	<div>
		<label for="notes" class="form-label">Notes</label>
		<textarea id="notes" bind:value={notes} class="textarea-base" rows="2" disabled={loading}
		></textarea>
	</div>

	<div class="flex flex-wrap items-center gap-x-6 gap-y-2">
		<div class="flex items-center gap-2">
			<input
				id="isPrimary"
				type="checkbox"
				bind:checked={isPrimary}
				class="h-4 w-4 rounded border-theme text-primary-600 focus:ring-primary-500"
				disabled={loading}
			/>
			<label for="isPrimary" class="text-sm text-theme">Primary Address</label>
		</div>
		{#if isEdit}
			<div class="flex items-center gap-2">
				<input
					id="isActive"
					type="checkbox"
					bind:checked={isActive}
					class="h-4 w-4 rounded border-theme text-primary-600 focus:ring-primary-500"
					disabled={loading}
				/>
				<label for="isActive" class="text-sm text-theme">Active</label>
			</div>
		{/if}
	</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}>
			{#if loading}
				Saving...
			{:else if isEdit}
				Update Address
			{:else}
				Add Address
			{/if}
		</button>
	</div>
</form>
