<script lang="ts">
	import {
		CreateCustomerContactStore,
		UpdateCustomerContactStore,
		CreateAccountContactStore,
		UpdateAccountContactStore
	} from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	interface Contact {
		id: string;
		firstName: string;
		lastName: string;
		email: string | null;
		phone: string | null;
		notes: string | null;
		isPrimary: boolean;
		isActive: boolean;
	}

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

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

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

	let firstName = $state(contact?.firstName ?? '');
	let lastName = $state(contact?.lastName ?? '');
	let email = $state(contact?.email ?? '');
	let phone = $state(contact?.phone ?? '');
	let notes = $state(contact?.notes ?? '');
	let isPrimary = $state(contact?.isPrimary ?? false);
	let isActive = $state(contact?.isActive ?? true);

	// Mutation stores
	const createCustomerStore = new CreateCustomerContactStore();
	const updateCustomerStore = new UpdateCustomerContactStore();
	const createAccountStore = new CreateAccountContactStore();
	const updateAccountStore = new UpdateAccountContactStore();

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

		try {
			if (!firstName || !lastName) {
				error = 'Please provide first and last name';
				return;
			}

			if (entityType === 'customer') {
				if (isEdit && contact) {
					const res = await updateCustomerStore.mutate({
						input: {
							id: contact.id,
							firstName,
							lastName,
							email: email || null,
							phone: phone || null,
							notes: notes || null,
							isPrimary
						}
					});
					if (res.errors?.length) {
						error = res.errors.map((e) => e.message).join(', ');
						return;
					}
				} else {
					const res = await createCustomerStore.mutate({
						input: {
							customerId: entityId,
							firstName,
							lastName,
							email,
							phone,
							notes,
							isPrimary,
							isActive: true
						}
					});
					if (res.errors?.length) {
						error = res.errors.map((e) => e.message).join(', ');
						return;
					}
				}
			} else {
				// Account
				if (isEdit && contact) {
					const res = await updateAccountStore.mutate({
						input: {
							id: contact.id,
							firstName,
							lastName,
							email,
							phone,
							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,
							firstName,
							lastName,
							email,
							phone,
							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 contact';
		} 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}>
		<div class="grid grid-cols-2 gap-4">
			<div>
				<label for="firstName" class="form-label">
					First Name <span class="required-indicator">*</span>
				</label>
				<input
					id="firstName"
					type="text"
					bind:value={firstName}
					disabled={submitting}
					placeholder="First name"
					class="input-base"
				/>
			</div>

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

		<div>
			<label for="email" class="form-label">Email</label>
			<input
				id="email"
				type="email"
				bind:value={email}
				disabled={submitting}
				placeholder="email@example.com"
				class="input-base"
			/>
		</div>

		<div>
			<label for="phone" class="form-label">Phone</label>
			<input
				id="phone"
				type="tel"
				bind:value={phone}
				disabled={submitting}
				placeholder="(555) 123-4567"
				class="input-base"
			/>
		</div>

		<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>

		<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 Contact</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 Contact'}
				{/if}
			</button>
			<button type="button" onclick={handleCancel} disabled={submitting} class="btn-cancel">
				Cancel
			</button>
		</div>
	</form>
</div>
