<script lang="ts">
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';
	import { enhance } from '$app/forms';
	import { invalidateAll } from '$app/navigation';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import type { WaveProduct } from './types';

	interface IncomeAccount {
		id: string;
		name: string;
		subtype: { value: string };
	}

	interface Props {
		product?: WaveProduct | null;
		incomeAccounts?: IncomeAccount[];
		onSuccess?: () => void;
	}

	let { product = null, incomeAccounts = [], onSuccess }: Props = $props();

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

	let name = $state(product?.name ?? '');
	let unitPrice = $state(product?.unitPrice?.toString() ?? '0');
	let description = $state(product?.description ?? '');

	// Default to existing product's income account, or find "Sales" account, or first available
	function getDefaultAccountId() {
		if (product?.incomeAccount?.id) return product.incomeAccount.id;
		const salesAccount = incomeAccounts.find((a) => a.name === 'Sales');
		if (salesAccount) return salesAccount.id;
		return incomeAccounts[0]?.id ?? '';
	}

	let incomeAccountId = $state(getDefaultAccountId());

	let isEditing = $derived(!!product);
</script>

<form
	method="POST"
	action={isEditing ? '?/updateProduct' : '?/createProduct'}
	use:enhance={() => {
		isSubmitting = true;
		error = '';
		return async ({ result }) => {
			isSubmitting = false;
			if (result.type === 'failure') {
				const errorMsg = result.data?.error;
				error = typeof errorMsg === 'string' ? errorMsg : 'An error occurred';
			} else if (result.type === 'success') {
				await invalidateAll();
				offCanvas.closeRight();
				onSuccess?.();
			}
		};
	}}
	class="flex h-full flex-col"
>
	{#if isEditing}
		<input type="hidden" name="id" value={product?.id} />
	{/if}

	<div class="flex-1 space-y-4">
		{#if error}
			<div class="rounded-lg border border-danger bg-danger p-3 text-sm text-danger">
				{error}
			</div>
		{/if}

		<div>
			<label for="name" class="mb-1.5 block text-sm font-medium text-theme">
				Name <span class="text-error-500">*</span>
			</label>
			<input
				type="text"
				id="name"
				name="name"
				bind:value={name}
				required
				class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent6-500 focus:ring-1 focus:ring-accent6-500"
				placeholder="Product or service name"
			/>
		</div>

		<div>
			<label for="unitPrice" class="mb-1.5 block text-sm font-medium text-theme">
				Unit Price
			</label>
			<div class="relative">
				<span class="absolute top-1/2 left-3 -translate-y-1/2 text-theme-muted">$</span>
				<input
					type="number"
					id="unitPrice"
					name="unitPrice"
					bind:value={unitPrice}
					min="0"
					step="0.01"
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme py-2 pr-3 pl-7 text-theme focus:border-accent6-500 focus:ring-1 focus:ring-accent6-500"
					placeholder="0.00"
				/>
			</div>
		</div>

		<div>
			<label for="description" class="mb-1.5 block text-sm font-medium text-theme">
				Description
			</label>
			<textarea
				id="description"
				name="description"
				bind:value={description}
				rows="3"
				class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent6-500 focus:ring-1 focus:ring-accent6-500"
				placeholder="Optional description"
			></textarea>
		</div>

		{#if incomeAccounts.length > 0}
			<div>
				<label for="incomeAccountId" class="mb-1.5 block text-sm font-medium text-theme">
					Income Account <span class="text-error-500">*</span>
				</label>
				<select
					id="incomeAccountId"
					name="incomeAccountId"
					bind:value={incomeAccountId}
					required
					class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-accent6-500 focus:ring-1 focus:ring-accent6-500"
				>
					{#each incomeAccounts as account (account.id)}
						<option value={account.id}>{account.name}</option>
					{/each}
				</select>
			</div>
		{/if}
	</div>

	<div class="mt-6 flex gap-3 border-t border-theme pt-4">
		<button
			type="button"
			onclick={() => offCanvas.closeRight()}
			disabled={isSubmitting}
			class="flex-1 rounded-lg border border-theme bg-theme px-4 py-2 text-sm font-medium text-theme transition-colors hover:bg-black/5 disabled:cursor-not-allowed disabled:opacity-50 dark:hover:bg-white/10"
		>
			Cancel
		</button>
		<button
			type="submit"
			disabled={isSubmitting || !name}
			class="flex flex-1 items-center justify-center gap-2 rounded-lg bg-accent6-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-accent6-600 disabled:cursor-not-allowed disabled:opacity-50"
		>
			{#if isSubmitting}
				<IconSpinner class="h-4 w-4" />
				<span>{isEditing ? 'Saving...' : 'Creating...'}</span>
			{:else}
				{isEditing ? 'Save Changes' : 'Create Product'}
			{/if}
		</button>
	</div>
</form>
