<script lang="ts">
	import {
		CreateCustomerAddressStore,
		UpdateCustomerAddressStore,
		CreateAccountAddressStore,
		UpdateAccountAddressStore
	} from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	interface Address {
		id: string;
		name?: string | null;
		streetAddress: string;
		city: string;
		state: string;
		zipCode: string;
		addressType?: string | null;
		isPrimary: boolean;
		isActive: boolean;
		notes?: string | null;
	}

	interface Props {
		entityType: 'customer' | 'account';
		entityId: string;
		address?: Address;
		showActiveToggle?: boolean;
		onSuccess?: () => void;
		onCancel?: () => void;
	}

	let {
		entityType,
		entityId,
		address,
		showActiveToggle = entityType === 'account',
		onSuccess,
		onCancel
	}: Props = $props();

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

	// Account-specific fields
	let name = $state(address?.name ?? '');
	let notes = $state(address?.notes ?? '');

	// Shared fields
	let streetAddress = $state(address?.streetAddress ?? '');
	let city = $state(address?.city ?? '');
	let stateValue = $state(address?.state ?? '');
	let zipCode = $state(address?.zipCode ?? '');
	let isPrimary = $state(address?.isPrimary ?? false);
	let isActive = $state(address?.isActive ?? true);

	// Customer-specific fields
	let addressType = $state(address?.addressType ?? 'BILLING');

	// Mutation stores
	const createCustomerStore = new CreateCustomerAddressStore();
	const updateCustomerStore = new UpdateCustomerAddressStore();
	const createAccountStore = new CreateAccountAddressStore();
	const updateAccountStore = new UpdateAccountAddressStore();

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

		try {
			if (!streetAddress || !city || !stateValue || !zipCode) {
				error = 'Please fill in all required address fields';
				return;
			}

			if (entityType === 'customer') {
				if (isEdit && address) {
					const res = await updateCustomerStore.mutate({
						input: {
							id: address.id,
							streetAddress,
							city,
							state: stateValue,
							zipCode,
							addressType,
							isPrimary
						}
					});
					if (res.errors?.length) {
						error = res.errors.map((e) => e.message).join(', ');
						return;
					}
				} else {
					const res = await createCustomerStore.mutate({
						input: {
							customerId: entityId,
							streetAddress,
							city,
							state: stateValue,
							zipCode,
							addressType,
							isPrimary,
							isActive: true
						}
					});
					if (res.errors?.length) {
						error = res.errors.map((e) => e.message).join(', ');
						return;
					}
				}
			} else {
				// Account
				if (isEdit && address) {
					const res = await updateAccountStore.mutate({
						input: {
							id: address.id,
							name,
							streetAddress,
							city,
							state: stateValue,
							zipCode,
							isPrimary,
							isActive,
							notes
						}
					});
					if (res.errors?.length) {
						error = res.errors.map((e) => e.message).join(', ');
						return;
					}
				} else {
					const res = await createAccountStore.mutate({
						input: {
							accountId: entityId,
							name,
							streetAddress,
							city,
							state: stateValue,
							zipCode,
							isPrimary,
							isActive,
							notes
						}
					});
					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 address';
		} 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="form-fields" onsubmit={handleSubmit}>
		{#if entityType === 'account'}
			<div>
				<label for="name" class="form-label">Location Name</label>
				<input
					id="name"
					type="text"
					bind:value={name}
					disabled={submitting}
					placeholder="e.g., Main Office, Warehouse"
					class="input-base"
				/>
			</div>
		{/if}

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

		<div class="grid grid-cols-2 gap-4">
			<div>
				<label for="city" class="form-label">
					City <span class="required-indicator">*</span>
				</label>
				<input
					id="city"
					type="text"
					bind:value={city}
					disabled={submitting}
					placeholder="City"
					class="input-base"
				/>
			</div>

			<div>
				<label for="state" class="form-label">
					State <span class="required-indicator">*</span>
				</label>
				<input
					id="state"
					type="text"
					bind:value={stateValue}
					disabled={submitting}
					placeholder="State"
					class="input-base"
				/>
			</div>
		</div>

		<div class="grid grid-cols-2 gap-4">
			<div>
				<label for="zipCode" class="form-label">
					ZIP Code <span class="required-indicator">*</span>
				</label>
				<input
					id="zipCode"
					type="text"
					bind:value={zipCode}
					disabled={submitting}
					placeholder="12345"
					class="input-base"
				/>
			</div>

			{#if entityType === 'customer'}
				<div>
					<label for="addressType" class="form-label">Address Type</label>
					<select
						id="addressType"
						bind:value={addressType}
						disabled={submitting}
						class="select-base"
					>
						<option value="BILLING">Billing</option>
						<option value="MAILING">Mailing</option>
						<option value="SERVICE">Service</option>
					</select>
				</div>
			{/if}
		</div>

		{#if entityType === 'account'}
			<div>
				<label for="notes" class="form-label">Notes</label>
				<textarea
					id="notes"
					bind:value={notes}
					disabled={submitting}
					rows="3"
					placeholder="Additional notes..."
					class="textarea-base"
				></textarea>
			</div>
		{/if}

		<div class="flex items-center gap-6">
			<label class="flex items-center gap-2">
				<input
					type="checkbox"
					bind:checked={isPrimary}
					disabled={submitting}
					class="checkbox-base"
				/>
				<span class="checkbox-label">Primary Address</span>
			</label>

			{#if showActiveToggle}
				<label class="flex items-center gap-2">
					<input
						type="checkbox"
						bind:checked={isActive}
						disabled={submitting}
						class="checkbox-base"
					/>
					<span class="checkbox-label">Active</span>
				</label>
			{/if}
		</div>

		<div class="form-actions">
			<button type="submit" disabled={submitting} class="btn-submit">
				{#if submitting}
					<span class="flex items-center justify-center gap-2">
						<IconSpinner class="h-4 w-4" />
						<span>{isEdit ? 'Saving...' : 'Adding...'}</span>
					</span>
				{:else}
					{isEdit ? 'Save Changes' : 'Add Address'}
				{/if}
			</button>
			<button type="button" onclick={handleCancel} disabled={submitting} class="btn-cancel">
				Cancel
			</button>
		</div>
	</form>
</div>
