<script lang="ts">
	import { CreateInvoiceStore, UpdateInvoiceStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { toGlobalId } from '$lib/utils/relay';
	import type { Customers$result } from '$houdini';

	type Customer = Customers$result['customers'][number];

	// Invoice can come from either AdminInvoices or GetInvoice query
	interface InvoiceData {
		id: string;
		date: string;
		customerId: string;
		status: string;
		datePaid?: string | null;
		paymentType?: string | null;
	}

	interface Props {
		customers: Customer[];
		invoice?: InvoiceData | null;
		onSuccess?: () => void;
		onCancel?: () => void;
	}

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

	let submitting = $state(false);
	let error = $state('');

	// Convert customerId (UUID) to GlobalID for the select dropdown
	function getCustomerGlobalId(customerId: string | undefined): string {
		if (!customerId) return '';
		// customerId is a UUID, need to convert to GlobalID to match customer.id
		return toGlobalId('CustomerType', customerId);
	}

	// Form fields
	let customerId = $state(getCustomerGlobalId(invoice?.customerId));
	let date = $state(invoice?.date ?? '');
	let status = $state(invoice?.status ?? 'DRAFT');
	let datePaid = $state(invoice?.datePaid ?? '');
	let paymentType = $state(invoice?.paymentType ?? '');

	// Active customers only
	let activeCustomers = $derived(customers.filter((c) => c.status === 'ACTIVE'));

	// Show payment fields when status is PAID
	let showPaymentFields = $derived(status === 'PAID');

	const createStore = new CreateInvoiceStore();
	const updateStore = new UpdateInvoiceStore();

	const statusOptions = [
		{ value: 'DRAFT', label: 'Draft' },
		{ value: 'SENT', label: 'Sent' },
		{ value: 'PAID', label: 'Paid' },
		{ value: 'OVERDUE', label: 'Overdue' },
		{ value: 'CANCELLED', label: 'Cancelled' }
	];

	const paymentTypeOptions = [
		{ value: '', label: 'Select payment type...' },
		{ value: 'CHECK', label: 'Check' },
		{ value: 'CREDIT_CARD', label: 'Credit Card' },
		{ value: 'BANK_TRANSFER', label: 'Bank Transfer' },
		{ value: 'CASH', label: 'Cash' }
	];

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

		try {
			if (!customerId || !date) {
				error = 'Please select a customer and date';
				return;
			}

			if (invoice) {
				// Update existing invoice
				const res = await updateStore.mutate({
					input: {
						id: invoice.id,
						customerId,
						date,
						status,
						datePaid: showPaymentFields && datePaid ? datePaid : null,
						paymentType: showPaymentFields && paymentType ? paymentType : null
					}
				});

				if (res.errors?.length) {
					error = res.errors.map((e: { message: string }) => e.message).join(', ');
					return;
				}
			} else {
				// Create new invoice
				const res = await createStore.mutate({
					input: {
						customerId,
						date,
						status,
						datePaid: showPaymentFields && datePaid ? datePaid : null,
						paymentType: showPaymentFields && paymentType ? paymentType : null
					}
				});

				if (res.errors?.length) {
					error = res.errors.map((e: { message: string }) => e.message).join(', ');
					return;
				}
			}

			offCanvas.closeRight();
			onSuccess?.();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to save invoice';
		} finally {
			submitting = false;
		}
	}

	function handleCancel() {
		offCanvas.closeRight();
		onCancel?.();
	}
</script>

<form onsubmit={handleSubmit} class="flex h-full flex-col">
	<div class="flex-1 space-y-6 overflow-y-auto p-6">
		<!-- Customer -->
		<div>
			<label for="customer" class="mb-1.5 block text-sm font-medium text-theme">Customer</label>
			<select
				id="customer"
				bind:value={customerId}
				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"
				required
			>
				<option value="">Select customer...</option>
				{#each activeCustomers as customer (customer.id)}
					<option value={customer.id}>{customer.name}</option>
				{/each}
			</select>
		</div>

		<!-- Date -->
		<div>
			<label for="date" class="mb-1.5 block text-sm font-medium text-theme">Invoice Date</label>
			<input
				type="date"
				id="date"
				bind:value={date}
				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"
				required
			/>
		</div>

		<!-- Status -->
		<div>
			<label for="status" class="mb-1.5 block text-sm font-medium text-theme">Status</label>
			<select
				id="status"
				bind:value={status}
				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"
			>
				{#each statusOptions as option (option.value)}
					<option value={option.value}>{option.label}</option>
				{/each}
			</select>
		</div>

		<!-- Payment fields (shown when status is PAID) -->
		{#if showPaymentFields}
			<div class="space-y-4 rounded-lg border border-theme bg-theme-secondary p-4">
				<h4 class="text-sm font-medium text-theme">Payment Details</h4>

				<!-- Date Paid -->
				<div>
					<label for="datePaid" class="mb-1.5 block text-sm font-medium text-theme">Date Paid</label
					>
					<input
						type="date"
						id="datePaid"
						bind:value={datePaid}
						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>

				<!-- Payment Type -->
				<div>
					<label for="paymentType" class="mb-1.5 block text-sm font-medium text-theme"
						>Payment Type</label
					>
					<select
						id="paymentType"
						bind:value={paymentType}
						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"
					>
						{#each paymentTypeOptions as option (option.value)}
							<option value={option.value}>{option.label}</option>
						{/each}
					</select>
				</div>
			</div>
		{/if}

		{#if error}
			<div class="rounded-lg bg-error-500/10 p-4">
				<p class="text-sm text-error-600 dark:text-error-400">{error}</p>
			</div>
		{/if}
	</div>

	<!-- Footer -->
	<div class="flex items-center justify-end gap-3 border-t border-theme bg-theme p-6">
		<button type="button" onclick={handleCancel} class="btn-ghost" disabled={submitting}>
			Cancel
		</button>
		<button type="submit" class="btn-primary" disabled={submitting || !customerId || !date}>
			{#if submitting}
				{invoice ? 'Updating...' : 'Creating...'}
			{:else}
				{invoice ? 'Update Invoice' : 'Create Invoice'}
			{/if}
		</button>
	</div>
</form>
