<script lang="ts">
	import { client } from '$lib/graphql/client';
	import { UPDATE_REVENUE, type UpdateRevenueInput } from '$lib/graphql/mutations/account';
	import { UPDATE_PROJECT, type UpdateProjectInput } from '$lib/graphql/mutations/project';

	interface WaveProduct {
		id: string;
		name: string;
		unitPrice: number;
		isArchived: boolean;
	}

	interface Props {
		type: 'revenue' | 'project';
		itemId: string;
		currentWaveServiceId: string | null;
		waveProducts: WaveProduct[];
		onSuccess: () => void;
		onCancel: () => void;
	}

	let { type, itemId, currentWaveServiceId, waveProducts, onSuccess, onCancel }: Props = $props();

	let activeProducts = $derived(waveProducts.filter((p) => !p.isArchived));
	let selectedProductId = $derived('');
	let loading = $state(false);
	let error = $state<string | null>(null);

	$effect(() => {
		selectedProductId = currentWaveServiceId ?? '';
	});

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

		try {
			// Empty string means clear the link
			const waveServiceId = selectedProductId || undefined;

			if (type === 'revenue') {
				const input: UpdateRevenueInput = { waveServiceId };
				await client.mutate({
					mutation: UPDATE_REVENUE,
					variables: { id: itemId, input }
				});
			} else {
				const input: UpdateProjectInput = { waveServiceId };
				await client.mutate({
					mutation: UPDATE_PROJECT,
					variables: { id: itemId, input }
				});
			}

			onSuccess();
		} catch (err) {
			console.error('Failed to update Wave link:', err);
			error = err instanceof Error ? err.message : 'Failed to update Wave link';
		} finally {
			loading = false;
		}
	}

	function getSelectedProductName(): string | null {
		if (!selectedProductId) return null;
		const product = waveProducts.find((p) => p.id === selectedProductId);
		return product?.name ?? null;
	}
</script>

<form onsubmit={handleSubmit} class="space-y-6">
	{#if error}
		<div class="rounded-lg bg-error-50 p-4 text-error-700 dark:bg-error-900/30 dark:text-error-300">
			{error}
		</div>
	{/if}

	<div>
		<label for="waveProduct" class="form-label">Wave Product</label>
		<select
			id="waveProduct"
			class="select-base"
			disabled={loading}
			onchange={(e) => (selectedProductId = e.currentTarget.value)}
		>
			<option value="" selected={!selectedProductId}>None</option>
			{#each activeProducts as product (product.id)}
				<option value={product.id} selected={selectedProductId === product.id}>
					{product.name} (${product.unitPrice.toFixed(2)})
				</option>
			{/each}
		</select>
		<p class="mt-1 text-xs text-theme-muted">
			{#if selectedProductId}
				This {type} will be linked to "{getSelectedProductName()}" for Wave invoicing.
			{:else}
				No Wave product linked. This {type} won't sync to Wave.
			{/if}
		</p>
	</div>

	<div class="flex justify-end gap-3">
		<button type="button" class="btn-secondary" onclick={onCancel} disabled={loading}>
			Cancel
		</button>
		<button type="submit" class="btn-primary" disabled={loading}>
			{#if loading}
				Saving...
			{:else}
				Save
			{/if}
		</button>
	</div>
</form>
