<script lang="ts">
	import { CreateCustomerStore, UpdateCustomerStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import type { GetCustomer$result } from '$houdini';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	type Customer = NonNullable<GetCustomer$result['customer']>;

	interface Props {
		customer?: Customer;
		onSuccess?: () => void;
		onCancel?: () => void;
	}

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

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

	let name = $state(customer?.name ?? '');
	let billingEmail = $state(customer?.billingEmail ?? '');
	let billingTerms = $state(customer?.billingTerms ?? '');
	let startDate = $state(customer?.startDate ?? '');
	let endDate = $state(customer?.endDate ?? '');
	let status = $state(customer?.status ?? 'ACTIVE');

	const createStore = new CreateCustomerStore();
	const updateStore = new UpdateCustomerStore();

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

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

			if (isEdit && customer) {
				const res = await updateStore.mutate({
					input: {
						id: customer.id,
						name,
						billingEmail,
						billingTerms,
						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,
						billingEmail,
						billingTerms,
						startDate,
						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 customer';
		} 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="space-y-4" onsubmit={handleSubmit}>
		<div>
			<label for="name" class="mb-1.5 block text-sm font-medium text-theme">
				Customer Name <span class="text-red-500">*</span>
			</label>
			<input
				id="name"
				type="text"
				bind:value={name}
				disabled={submitting}
				placeholder="Enter customer 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="billingEmail" class="mb-1.5 block text-sm font-medium text-theme">
				Billing Email <span class="text-red-500">*</span>
			</label>
			<input
				id="billingEmail"
				type="email"
				bind:value={billingEmail}
				disabled={submitting}
				placeholder="Enter billing email"
				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="billingTerms" class="mb-1.5 block text-sm font-medium text-theme">
				Billing Terms
			</label>
			<input
				id="billingTerms"
				type="text"
				bind:value={billingTerms}
				disabled={submitting}
				placeholder="Enter billing terms (optional)"
				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-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 Customer'}
				{/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>
