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

	interface Account {
		id: string;
		name: string;
		status: string;
		startDate?: string | null;
		endDate?: string | null;
	}

	interface Revenue {
		id: string;
		amount: string;
		startDate: string;
		waveServiceId?: string | null;
	}

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

	interface Props {
		account: Account;
		activeRevenue?: Revenue | null;
		waveProducts?: WaveProduct[];
		onSuccess: () => void;
		onCancel: () => void;
	}

	let { account, activeRevenue = null, waveProducts = [], onSuccess, onCancel }: Props = $props();

	let activeWaveProducts = $derived(waveProducts.filter((p) => !p.isArchived));

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

	// Revenue state
	let revenueAmount = $state('');
	let waveServiceId = $state('');
	let isNewRate = $state(false);

	$effect(() => {
		name = account.name;
		status = account.status;
		startDate = account.startDate ?? '';
		endDate = account.endDate ?? '';
		revenueAmount = activeRevenue?.amount ?? '';
		waveServiceId = activeRevenue?.waveServiceId ?? '';
		isNewRate = false;
	});

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

	// Check if revenue has changed
	let revenueChanged = $derived(
		activeRevenue
			? revenueAmount !== activeRevenue.amount ||
					waveServiceId !== (activeRevenue.waveServiceId ?? '')
			: revenueAmount !== ''
	);

	function getTodayDate(): string {
		return new Date().toISOString().split('T')[0];
	}

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

		try {
			// Update account info
			const input: UpdateAccountInput = {
				name: name || undefined,
				status: (status as UpdateAccountInput['status']) || undefined,
				startDate: startDate || undefined,
				endDate: endDate || undefined
			};

			await client.mutate({
				mutation: UPDATE_ACCOUNT,
				variables: { id: account.id, input }
			});

			// Handle revenue
			if (revenueAmount && revenueChanged) {
				const amount = parseFloat(revenueAmount);
				if (!isNaN(amount)) {
					if (activeRevenue && isNewRate) {
						// Mark old revenue as inactive, create new one
						await client.mutate({
							mutation: UPDATE_REVENUE,
							variables: {
								id: activeRevenue.id,
								input: { endDate: getTodayDate(), isActive: false } as UpdateRevenueInput
							}
						});
						const revenueInput: CreateRevenueInput = {
							amount,
							startDate: getTodayDate(),
							waveServiceId: waveServiceId || undefined
						};
						await client.mutate({
							mutation: CREATE_REVENUE,
							variables: { accountId: account.id, input: revenueInput }
						});
					} else if (activeRevenue) {
						// Update existing revenue
						const revenueInput: UpdateRevenueInput = {
							amount,
							waveServiceId: waveServiceId || undefined
						};
						await client.mutate({
							mutation: UPDATE_REVENUE,
							variables: { id: activeRevenue.id, input: revenueInput }
						});
					} else {
						// Create new revenue
						const revenueInput: CreateRevenueInput = {
							amount,
							startDate: getTodayDate(),
							waveServiceId: waveServiceId || undefined
						};
						await client.mutate({
							mutation: CREATE_REVENUE,
							variables: { accountId: account.id, input: revenueInput }
						});
					}
				}
			}

			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="name" class="form-label">
			Account Name <span class="required-indicator">*</span>
		</label>
		<input id="name" type="text" bind:value={name} class="input-base" required disabled={loading} />
	</div>

	<div>
		<label for="status" class="form-label">Status</label>
		<select id="status" bind:value={status} class="input-base" disabled={loading}>
			<option value="ACTIVE">Active</option>
			<option value="INACTIVE">Inactive</option>
			<option value="PENDING">Pending</option>
		</select>
	</div>

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

	<!-- Monthly Revenue -->
	<div class="border-t border-theme pt-5">
		<h3 class="mb-3 text-sm font-medium text-theme">Monthly Revenue</h3>

		<div class="space-y-4">
			<div>
				<label for="revenueAmount" 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="revenueAmount"
						type="number"
						step="0.01"
						min="0"
						bind:value={revenueAmount}
						class="input-base pl-7"
						disabled={loading}
						placeholder="0.00"
					/>
				</div>
			</div>

			<div>
				<label for="waveServiceId" class="form-label">Wave Product</label>
				<select id="waveServiceId" bind:value={waveServiceId} class="input-base" disabled={loading}>
					<option value="">None</option>
					{#each activeWaveProducts as product (product.id)}
						<option value={product.id}>{product.name} (${product.unitPrice.toFixed(2)})</option>
					{/each}
				</select>
				<p class="mt-1 text-xs text-theme-muted">Wave accounting product for invoicing</p>
			</div>

			{#if activeRevenue && revenueChanged}
				<label
					class="bg-theme-secondary/50 flex items-start gap-3 rounded-lg border border-theme p-3"
				>
					<input
						type="checkbox"
						bind:checked={isNewRate}
						class="border-theme-muted mt-0.5 h-4 w-4 rounded text-primary-600 focus:ring-primary-500"
						disabled={loading}
					/>
					<div>
						<span class="text-sm font-medium text-theme">This is a new rate</span>
						<p class="text-xs text-theme-muted">
							Check this if the rate changed. The previous rate will be kept in history.
						</p>
					</div>
				</label>
			{/if}
		</div>
	</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}
				Update Account
			{/if}
		</button>
	</div>
</form>
