<script lang="ts">
	import { client } from '$lib/graphql/client';
	import {
		CREATE_REVENUE,
		UPDATE_REVENUE,
		type CreateRevenueInput,
		type UpdateRevenueInput
	} from '$lib/graphql/mutations/account';
	import type { AccountRevenue } from '$lib/graphql/queries/account';

	interface Props {
		revenue?: AccountRevenue;
		accountId: string;
		onSuccess: () => void;
		onCancel: () => void;
	}

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

	let isEdit = $derived(!!revenue);

	// Form state - use $effect to sync from props
	let amount = $state('');
	let startDate = $state('');
	let endDate = $state('');
	let waveServiceId = $state('');

	$effect(() => {
		amount = revenue?.amount ?? '';
		startDate = revenue?.startDate ?? new Date().toISOString().split('T')[0];
		endDate = revenue?.endDate ?? '';
		waveServiceId = revenue?.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 = parseFloat(String(amount));
			if (isNaN(amountNum) || amountNum < 0) {
				throw new Error('Please enter a valid amount');
			}

			if (isEdit && revenue) {
				const input: UpdateRevenueInput = {
					amount: amountNum,
					startDate: startDate || undefined,
					endDate: endDate || undefined,
					waveServiceId: waveServiceId || undefined
				};

				await client.mutate({
					mutation: UPDATE_REVENUE,
					variables: { id: revenue.id, input }
				});
			} else {
				const input: CreateRevenueInput = {
					amount: amountNum,
					startDate,
					waveServiceId: waveServiceId || undefined
				};

				await client.mutate({
					mutation: CREATE_REVENUE,
					variables: { accountId, 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}

	{#if !isEdit}
		<div
			class="rounded-lg border border-warning-500/30 bg-warning-50/50 p-3 dark:bg-warning-950/30"
		>
			<p class="text-sm text-warning-700 dark:text-warning-400">
				Creating a new rate will end the current active rate as of today.
			</p>
		</div>
	{/if}

	<div>
		<label for="amount" class="form-label">
			Monthly Amount <span class="required-indicator">*</span>
		</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"
				required
				disabled={loading}
				placeholder="0.00"
			/>
		</div>
	</div>

	<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
		<div>
			<label for="startDate" class="form-label">
				Start Date <span class="required-indicator">*</span>
			</label>
			<input
				id="startDate"
				type="date"
				bind:value={startDate}
				class="input-base"
				required
				disabled={loading}
			/>
		</div>
		{#if isEdit}
			<div>
				<label for="endDate" class="form-label">End Date</label>
				<input
					id="endDate"
					type="date"
					bind:value={endDate}
					class="input-base"
					disabled={loading}
				/>
			</div>
		{/if}
	</div>

	<div>
		<label for="waveServiceId" class="form-label">Wave Service ID</label>
		<input
			id="waveServiceId"
			type="text"
			bind:value={waveServiceId}
			class="input-base"
			disabled={loading}
			placeholder="Optional - for Wave integration"
		/>
	</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 if isEdit}
				Update Revenue
			{:else}
				Add Revenue
			{/if}
		</button>
	</div>
</form>
