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

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

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

	// Form state
	let name = $state('');
	let status = $state<'ACTIVE' | 'INACTIVE' | 'PENDING'>('ACTIVE');
	let billingEmail = $state('');
	let billingTerms = $state('');
	let waveCustomerId = $state('');
	let startDate = $state('');
	let endDate = $state('');

	// Billing address state
	let streetAddress = $state('');
	let city = $state('');
	let stateCode = $state('');
	let zipCode = $state('');

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

	// Check if address fields have any content
	let hasAddressData = $derived(
		streetAddress.trim() !== '' || city.trim() !== '' || stateCode.trim() !== ''
	);

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

		try {
			// Create customer
			const input: CreateCustomerInput = {
				name,
				status,
				billingEmail: billingEmail || undefined,
				billingTerms: billingTerms || undefined,
				waveCustomerId: waveCustomerId || undefined,
				startDate: startDate || undefined,
				endDate: endDate || undefined
			};

			const result = await client.mutate<{ createCustomer: { id: string } }>({
				mutation: CREATE_CUSTOMER,
				variables: { input }
			});

			const customerId = result.data?.createCustomer?.id;
			if (!customerId) {
				throw new Error('Failed to create customer');
			}

			// Create billing address if provided
			if (hasAddressData && streetAddress && city && stateCode && zipCode) {
				const addressInput: CreateCustomerAddressInput = {
					streetAddress,
					city,
					state: stateCode,
					zipCode,
					isPrimary: true
				};
				await client.mutate({
					mutation: CREATE_CUSTOMER_ADDRESS,
					variables: { customerId, input: addressInput }
				});
			}

			onSuccess(customerId);
		} 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">
			Customer Name <span class="required-indicator">*</span>
		</label>
		<input id="name" type="text" bind:value={name} class="input-base" required disabled={loading} />
	</div>

	<div>
		<label for="status" class="form-label">Status</label>
		<select id="status" bind:value={status} class="select-base" disabled={loading}>
			<option value="ACTIVE">Active</option>
			<option value="INACTIVE">Inactive</option>
			<option value="PENDING">Pending</option>
		</select>
	</div>

	<div>
		<label for="billingEmail" class="form-label">Billing Email</label>
		<input
			id="billingEmail"
			type="email"
			bind:value={billingEmail}
			class="input-base"
			disabled={loading}
		/>
	</div>

	<div>
		<label for="billingTerms" class="form-label">Billing Terms</label>
		<input
			id="billingTerms"
			type="text"
			bind:value={billingTerms}
			class="input-base"
			placeholder="e.g., Net 30"
			disabled={loading}
		/>
	</div>

	<div>
		<label for="waveCustomerId" class="form-label">Wave Customer ID</label>
		<input
			id="waveCustomerId"
			type="text"
			bind:value={waveCustomerId}
			class="input-base"
			placeholder="Enter Wave customer ID..."
			disabled={loading}
		/>
		<p class="mt-1 text-xs text-theme-muted">Wave accounting customer ID for invoicing</p>
	</div>

	<!-- Billing Address -->
	<div class="border-t border-theme pt-5">
		<h3 class="mb-3 text-sm font-medium text-theme">Billing Address</h3>
		<p class="mb-4 text-xs text-theme-muted">Optional. You can add this later.</p>

		<div class="space-y-4">
			<div>
				<label for="streetAddress" class="form-label">Street Address</label>
				<input
					id="streetAddress"
					type="text"
					bind:value={streetAddress}
					class="input-base"
					disabled={loading}
					placeholder="123 Main St"
				/>
			</div>

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

				<div>
					<label for="stateCode" class="form-label">State</label>
					<input
						id="stateCode"
						type="text"
						bind:value={stateCode}
						class="input-base"
						disabled={loading}
						placeholder="CA"
						maxlength="2"
					/>
				</div>
			</div>

			<div class="w-1/2">
				<label for="zipCode" class="form-label">ZIP Code</label>
				<input
					id="zipCode"
					type="text"
					bind:value={zipCode}
					class="input-base"
					disabled={loading}
					placeholder="12345"
					maxlength="10"
				/>
			</div>
		</div>
	</div>

	<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
		<div>
			<label for="startDate" class="form-label">Start Date</label>
			<input
				id="startDate"
				type="date"
				bind:value={startDate}
				class="input-base"
				disabled={loading}
			/>
		</div>
		<div>
			<label for="endDate" class="form-label">End Date</label>
			<input id="endDate" type="date" bind:value={endDate} class="input-base" disabled={loading} />
		</div>
	</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}
				Creating...
			{:else}
				Create Customer
			{/if}
		</button>
	</div>
</form>
