<script lang="ts">
	import { client } from '$lib/graphql/client';
	import { CREATE_LABOR, UPDATE_LABOR } from '$lib/graphql/mutations/location';
	import type { AddressLabor } from '$lib/graphql/queries/account';

	interface Props {
		labor?: AddressLabor | null;
		accountAddressId: string;
		onSuccess: () => void;
		onCancel: () => void;
	}

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

	let isEdit = $derived(!!labor);

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

	$effect(() => {
		amount = labor?.amount ?? '';
		startDate = labor?.startDate ?? new Date().toISOString().split('T')[0];
	});

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

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

		try {
			if (isEdit && labor) {
				await client.mutate({
					mutation: UPDATE_LABOR,
					variables: {
						id: labor.id,
						input: {
							amount: amount ? parseFloat(amount) : undefined,
							startDate: startDate || undefined
						}
					}
				});
			} else {
				await client.mutate({
					mutation: CREATE_LABOR,
					variables: {
						accountAddressId,
						input: {
							amount: parseFloat(amount),
							startDate
						}
					}
				});
			}

			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 <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>
		<p class="mt-1 text-xs text-theme-muted">Hourly labor rate paid for this location</p>
	</div>

	<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}
		/>
		<p class="mt-1 text-xs text-theme-muted">When this rate becomes effective</p>
	</div>

	{#if !isEdit}
		<div
			class="rounded-lg border border-primary-500/30 bg-primary-50/50 p-3 dark:bg-primary-950/30"
		>
			<p class="text-sm text-primary-700 dark:text-primary-400">
				Creating a new labor rate will automatically end any existing active rate.
			</p>
		</div>
	{/if}

	<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 Labor Rate
			{:else}
				Add Labor Rate
			{/if}
		</button>
	</div>
</form>
