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

	interface Location {
		id: string;
		name?: string | null;
		streetAddress: string;
		city: string;
		state: string;
		zipCode: string;
		notes?: string | null;
		isPrimary: boolean;
		isActive: boolean;
	}

	interface Labor {
		id: string;
		amount: string;
		startDate: string;
	}

	interface Props {
		location: Location;
		activeLabor?: Labor | null;
		onSuccess: () => void;
		onCancel: () => void;
	}

	let { location, activeLabor = null, onSuccess, onCancel }: Props = $props();

	// Form state - use $effect to sync from props
	let name = $state('');
	let streetAddress = $state('');
	let city = $state('');
	let stateCode = $state('');
	let zipCode = $state('');
	let notes = $state('');
	let isPrimary = $state(false);
	let isActive = $state(true);

	// Labor state
	let laborAmount = $state('');
	let isNewRate = $state(false);

	$effect(() => {
		name = location.name ?? '';
		streetAddress = location.streetAddress;
		city = location.city;
		stateCode = location.state;
		zipCode = location.zipCode;
		notes = location.notes ?? '';
		isPrimary = location.isPrimary;
		isActive = location.isActive;
		laborAmount = activeLabor?.amount ?? '';
		isNewRate = false;
	});

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

	// Check if labor has changed
	let laborChanged = $derived(
		activeLabor ? laborAmount !== activeLabor.amount : laborAmount !== ''
	);

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

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

		try {
			// Update location
			await client.mutate({
				mutation: UPDATE_ACCOUNT_ADDRESS,
				variables: {
					id: location.id,
					input: {
						name: name.trim(),
						streetAddress,
						city,
						state: stateCode,
						zipCode,
						notes: notes.trim() || null,
						isPrimary,
						isActive
					}
				}
			});

			// Handle labor
			if (laborAmount && laborChanged) {
				const amount = parseFloat(laborAmount);
				if (!isNaN(amount)) {
					if (activeLabor && isNewRate) {
						// Mark old labor as inactive, create new one
						await client.mutate({
							mutation: UPDATE_LABOR,
							variables: {
								id: activeLabor.id,
								input: { endDate: getTodayDate(), isActive: false }
							}
						});
						await client.mutate({
							mutation: CREATE_LABOR,
							variables: {
								accountAddressId: location.id,
								input: { amount, startDate: getTodayDate() }
							}
						});
					} else if (activeLabor) {
						// Update existing labor
						await client.mutate({
							mutation: UPDATE_LABOR,
							variables: {
								id: activeLabor.id,
								input: { amount }
							}
						});
					} else {
						// Create new labor
						await client.mutate({
							mutation: CREATE_LABOR,
							variables: {
								accountAddressId: location.id,
								input: { amount, startDate: getTodayDate() }
							}
						});
					}
				}
			}

			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">Location Name</label>
		<input
			id="name"
			type="text"
			bind:value={name}
			class="input-base"
			disabled={loading}
			placeholder="e.g., Main Office, Building A"
		/>
		<p class="mt-1 text-xs text-theme-muted">Optional friendly name for this location</p>
	</div>

	<div>
		<label for="streetAddress" class="form-label">
			Street Address <span class="required-indicator">*</span>
		</label>
		<input
			id="streetAddress"
			type="text"
			bind:value={streetAddress}
			class="input-base"
			required
			disabled={loading}
			placeholder="123 Main Street"
		/>
	</div>

	<div class="grid grid-cols-6 gap-4">
		<div class="col-span-3">
			<label for="city" class="form-label">
				City <span class="required-indicator">*</span>
			</label>
			<input
				id="city"
				type="text"
				bind:value={city}
				class="input-base"
				required
				disabled={loading}
				placeholder="City"
			/>
		</div>

		<div class="col-span-1">
			<label for="state" class="form-label">
				State <span class="required-indicator">*</span>
			</label>
			<input
				id="state"
				type="text"
				bind:value={stateCode}
				class="input-base"
				required
				disabled={loading}
				placeholder="CA"
				maxlength="2"
			/>
		</div>

		<div class="col-span-2">
			<label for="zipCode" class="form-label">
				ZIP <span class="required-indicator">*</span>
			</label>
			<input
				id="zipCode"
				type="text"
				bind:value={zipCode}
				class="input-base"
				required
				disabled={loading}
				placeholder="12345"
			/>
		</div>
	</div>

	<div>
		<label for="notes" class="form-label">Notes</label>
		<textarea
			id="notes"
			bind:value={notes}
			class="textarea-base"
			rows="3"
			disabled={loading}
			placeholder="Access instructions, parking info, etc."
		></textarea>
	</div>

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

		<div class="space-y-4">
			<div>
				<label for="laborAmount" 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="laborAmount"
						type="number"
						step="0.01"
						min="0"
						bind:value={laborAmount}
						class="input-base pl-7"
						disabled={loading}
						placeholder="0.00"
					/>
				</div>
				<p class="mt-1 text-xs text-theme-muted">Amount paid to cleaners for this location</p>
			</div>

			{#if activeLabor && laborChanged}
				<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="flex flex-col gap-3">
		<label class="flex cursor-pointer items-center gap-2">
			<input type="checkbox" bind:checked={isPrimary} class="checkbox-base" disabled={loading} />
			<span class="text-sm text-theme">Primary Location</span>
		</label>
		<p class="-mt-2 ml-6 text-xs text-theme-muted">
			Primary location is used as the default for billing and communications
		</p>

		<label class="flex cursor-pointer items-center gap-2">
			<input type="checkbox" bind:checked={isActive} class="checkbox-base" disabled={loading} />
			<span class="text-sm text-theme">Active</span>
		</label>
		<p class="-mt-2 ml-6 text-xs text-theme-muted">
			Inactive locations are hidden from day-to-day operations
		</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}
				Update Location
			{/if}
		</button>
	</div>
</form>
