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

	interface Project {
		id: string;
		name: string;
		date: string;
		status: WorkStatus;
		labor?: number | null;
		amount?: number | null;
		waveServiceId?: string | null;
		calendarEventId?: string | null;
		notes?: string | null;
	}

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

	interface Props {
		project: Project;
		waveProducts?: WaveProduct[];
		onSuccess: () => void;
		onCancel: () => void;
	}

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

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

	// Form state - use $effect to sync from props
	let name = $state('');
	let date = $state('');
	let status = $state<WorkStatus>('SCHEDULED');
	let labor = $state<string>('');
	let amount = $state<string>('');
	let waveServiceId = $state('');
	let calendarEventId = $state('');
	let notes = $state('');

	$effect(() => {
		name = project.name;
		date = project.date;
		status = project.status;
		labor = project.labor?.toString() ?? '';
		amount = project.amount?.toString() ?? '';
		waveServiceId = project.waveServiceId ?? '';
		calendarEventId = project.calendarEventId ?? '';
		notes = project.notes ?? '';
	});

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

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

		try {
			const laborNum = labor ? parseFloat(labor) : undefined;
			const amountNum = amount ? parseFloat(amount) : undefined;

			const input: UpdateProjectInput = {
				name: name || undefined,
				date: date || undefined,
				status: status || undefined,
				labor: laborNum,
				amount: amountNum,
				waveServiceId: waveServiceId || undefined,
				calendarEventId: calendarEventId, // Allow empty string to clear
				notes: notes || 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="name" class="form-label">
			Project 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="date" class="form-label">
			Project Date <span class="required-indicator">*</span>
		</label>
		<input id="date" type="date" bind:value={date} 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="SCHEDULED">Scheduled</option>
			<option value="IN_PROGRESS">In Progress</option>
			<option value="COMPLETED">Completed</option>
			<option value="CANCELLED">Cancelled</option>
		</select>
	</div>

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

	<div>
		<label for="amount" class="form-label">Amount ($ Invoice)</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>
		<p class="mt-1 text-xs text-theme-muted">Invoice amount for this project</p>
	</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 activeProducts 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>

	<div>
		<label for="calendarEventId" class="form-label">Calendar Event ID</label>
		<input
			id="calendarEventId"
			type="text"
			bind:value={calendarEventId}
			class="input-base"
			disabled={loading}
			placeholder="Enter calendar event ID..."
		/>
		<p class="mt-1 text-xs text-theme-muted">Google Calendar event ID for scheduling</p>
	</div>

	<div>
		<label for="notes" class="form-label">Notes</label>
		<textarea
			id="notes"
			bind:value={notes}
			class="textarea-base"
			rows="4"
			disabled={loading}
			placeholder="Add any notes about this project..."
		></textarea>
	</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 Project
			{/if}
		</button>
	</div>
</form>
