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

	interface Project {
		id: string;
		amount?: number | null;
		waveServiceId?: string | null;
	}

	interface Props {
		project: Project;
		onSuccess: () => void;
		onCancel: () => void;
	}

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

	// Form state - use $effect to sync from props
	let amount = $state<string>('');
	let waveServiceId = $state('');

	$effect(() => {
		amount = project.amount?.toString() ?? '';
		waveServiceId = project.waveServiceId ?? '';
	});

	let loading = $state(false);
	let error = $state<string | null>(null);

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

		try {
			const amountNum = amount ? parseFloat(amount) : undefined;
			if (amount && (isNaN(amountNum!) || amountNum! < 0)) {
				throw new Error('Please enter a valid amount');
			}

			const input: UpdateProjectInput = {
				amount: amountNum,
				waveServiceId: waveServiceId || undefined
			};

			await client.mutate({
				mutation: UPDATE_PROJECT,
				variables: { id: project.id, input }
			});

			onSuccess();
		} catch (err) {
			error = err instanceof Error ? err.message : 'An error occurred';
		} finally {
			loading = false;
		}
	}
</script>

<form onsubmit={handleSubmit} class="space-y-5">
	{#if error}
		<div class="rounded-lg border border-error-500/30 bg-error-50/50 p-3 dark:bg-error-950/30">
			<p class="text-sm text-error-700 dark:text-error-400">{error}</p>
		</div>
	{/if}

	<div>
		<label for="amount" class="form-label">Amount</label>
		<div class="relative">
			<span class="absolute top-1/2 left-3 -translate-y-1/2 text-theme-muted">$</span>
			<input
				id="amount"
				type="number"
				step="0.01"
				min="0"
				bind:value={amount}
				class="input-base pl-7"
				disabled={loading}
				placeholder="0.00"
			/>
		</div>
	</div>

	<div>
		<label for="waveServiceId" class="form-label">
			Wave Product ID
			<span
				class="ml-1 inline-flex rounded-full bg-primary-100 px-2 py-0.5 text-xs font-semibold text-primary-800 dark:bg-primary-900/30 dark:text-primary-400"
			>
				Wave
			</span>
		</label>
		<input
			id="waveServiceId"
			type="text"
			bind:value={waveServiceId}
			class="input-base"
			disabled={loading}
			placeholder="Enter Wave product ID"
		/>
		<p class="mt-1 text-xs text-theme-muted">Link to Wave accounting product for invoicing</p>
	</div>

	<div class="form-actions border-t border-theme pt-5">
		<button type="button" class="btn-cancel" onclick={onCancel} disabled={loading}>Cancel</button>
		<button type="submit" class="btn-submit" disabled={loading}>
			{#if loading}
				Saving...
			{:else}
				Save Amount
			{/if}
		</button>
	</div>
</form>
