<script lang="ts">
	import { CreateScheduleStore, UpdateScheduleStore } from '$houdini';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import type { GetAccount$result } from '$houdini';
	import IconSpinner from '$lib/components/icons/IconSpinner.svelte';

	type Schedule = NonNullable<
		GetAccount$result['account']
	>['addresses'][number]['schedules'][number];

	interface Props {
		accountAddressId: string;
		schedule?: Schedule;
		onSuccess?: () => void;
		onCancel?: () => void;
	}

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

	let isEdit = $derived(!!schedule);
	let submitting = $state(false);
	let error = $state('');

	// Form fields
	let name = $state(schedule?.name ?? '');
	let startDate = $state(schedule?.startDate ?? '');
	let endDate = $state(schedule?.endDate ?? '');
	let mondayService = $state(schedule?.mondayService ?? false);
	let tuesdayService = $state(schedule?.tuesdayService ?? false);
	let wednesdayService = $state(schedule?.wednesdayService ?? false);
	let thursdayService = $state(schedule?.thursdayService ?? false);
	let fridayService = $state(schedule?.fridayService ?? false);
	let saturdayService = $state(schedule?.saturdayService ?? false);
	let sundayService = $state(schedule?.sundayService ?? false);
	let weekendService = $state(schedule?.weekendService ?? false);
	let scheduleException = $state(schedule?.scheduleException ?? '');

	const createStore = new CreateScheduleStore();
	const updateStore = new UpdateScheduleStore();

	// When weekend service is toggled on, clear Fri/Sat/Sun
	function handleWeekendServiceChange(checked: boolean) {
		weekendService = checked;
		if (checked) {
			fridayService = false;
			saturdayService = false;
			sundayService = false;
		}
	}

	// When any of Fri/Sat/Sun is toggled on, clear weekend service
	function handleWeekendDayChange(day: 'friday' | 'saturday' | 'sunday', checked: boolean) {
		if (day === 'friday') fridayService = checked;
		if (day === 'saturday') saturdayService = checked;
		if (day === 'sunday') sundayService = checked;
		if (checked) {
			weekendService = false;
		}
	}

	async function handleSubmit(e: SubmitEvent) {
		e.preventDefault();
		submitting = true;
		error = '';

		try {
			if (!startDate) {
				error = 'Please provide a start date';
				return;
			}

			const hasAnyService =
				mondayService ||
				tuesdayService ||
				wednesdayService ||
				thursdayService ||
				fridayService ||
				saturdayService ||
				sundayService ||
				weekendService;

			if (!hasAnyService) {
				error = 'Please select at least one service day or weekend service';
				return;
			}

			if (isEdit && schedule) {
				const res = await updateStore.mutate({
					input: {
						id: schedule.id,
						accountAddressId,
						name: name || null,
						startDate,
						endDate: endDate || null,
						mondayService,
						tuesdayService,
						wednesdayService,
						thursdayService,
						fridayService,
						saturdayService,
						sundayService,
						weekendService,
						scheduleException: scheduleException || null
					}
				});
				if (res.errors?.length) {
					error = res.errors.map((e) => e.message).join(', ');
					return;
				}
			} else {
				const res = await createStore.mutate({
					input: {
						accountAddressId,
						name: name || null,
						startDate,
						endDate: endDate || null,
						mondayService,
						tuesdayService,
						wednesdayService,
						thursdayService,
						fridayService,
						saturdayService,
						sundayService,
						weekendService,
						scheduleException: scheduleException || null
					}
				});
				if (res.errors?.length) {
					error = res.errors.map((e) => e.message).join(', ');
					return;
				}
			}

			offCanvas.closeRight();
			onSuccess?.();
		} catch (err) {
			error = err instanceof Error ? err.message : 'Failed to save schedule';
		} finally {
			submitting = false;
		}
	}

	function handleCancel() {
		offCanvas.closeRight();
		onCancel?.();
	}

	const dayCheckboxClass =
		'h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50';
</script>

<div class="min-w-0 space-y-6">
	{#if error}
		<div class="alert-error">
			{error}
		</div>
	{/if}

	<form class="space-y-4" onsubmit={handleSubmit}>
		<!-- Name -->
		<div>
			<label for="name" class="mb-1.5 block text-sm font-medium text-theme"> Schedule Name </label>
			<input
				id="name"
				type="text"
				bind:value={name}
				disabled={submitting}
				placeholder="e.g., Summer Schedule"
				class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
			/>
		</div>

		<!-- Dates -->
		<div class="grid grid-cols-2 gap-4">
			<div>
				<label for="startDate" class="mb-1.5 block text-sm font-medium text-theme">
					Start Date <span class="text-red-500">*</span>
				</label>
				<input
					id="startDate"
					type="date"
					bind:value={startDate}
					disabled={submitting}
					class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
				/>
			</div>

			<div>
				<label for="endDate" class="mb-1.5 block text-sm font-medium text-theme"> End Date </label>
				<input
					id="endDate"
					type="date"
					bind:value={endDate}
					disabled={submitting}
					class="w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
				/>
			</div>
		</div>

		<p class="text-xs text-theme-muted">
			Leave end date empty to mark this as the current active schedule.
		</p>

		<!-- Service Days -->
		<div>
			<p class="mb-2 text-sm font-medium text-theme">
				Service Days <span class="text-red-500">*</span>
			</p>

			<!-- Weekday checkboxes -->
			<div class="grid grid-cols-4 gap-3">
				<label class="flex items-center gap-2">
					<input
						type="checkbox"
						bind:checked={mondayService}
						disabled={submitting}
						class={dayCheckboxClass}
					/>
					<span class="text-sm text-theme">Mon</span>
				</label>

				<label class="flex items-center gap-2">
					<input
						type="checkbox"
						bind:checked={tuesdayService}
						disabled={submitting}
						class={dayCheckboxClass}
					/>
					<span class="text-sm text-theme">Tue</span>
				</label>

				<label class="flex items-center gap-2">
					<input
						type="checkbox"
						bind:checked={wednesdayService}
						disabled={submitting}
						class={dayCheckboxClass}
					/>
					<span class="text-sm text-theme">Wed</span>
				</label>

				<label class="flex items-center gap-2">
					<input
						type="checkbox"
						bind:checked={thursdayService}
						disabled={submitting}
						class={dayCheckboxClass}
					/>
					<span class="text-sm text-theme">Thu</span>
				</label>

				<label class="flex items-center gap-2">
					<input
						type="checkbox"
						checked={fridayService}
						onchange={(e) => handleWeekendDayChange('friday', e.currentTarget.checked)}
						disabled={submitting || weekendService}
						class={dayCheckboxClass}
					/>
					<span class="text-sm text-theme {weekendService ? 'opacity-50' : ''}">Fri</span>
				</label>

				<label class="flex items-center gap-2">
					<input
						type="checkbox"
						checked={saturdayService}
						onchange={(e) => handleWeekendDayChange('saturday', e.currentTarget.checked)}
						disabled={submitting || weekendService}
						class={dayCheckboxClass}
					/>
					<span class="text-sm text-theme {weekendService ? 'opacity-50' : ''}">Sat</span>
				</label>

				<label class="flex items-center gap-2">
					<input
						type="checkbox"
						checked={sundayService}
						onchange={(e) => handleWeekendDayChange('sunday', e.currentTarget.checked)}
						disabled={submitting || weekendService}
						class={dayCheckboxClass}
					/>
					<span class="text-sm text-theme {weekendService ? 'opacity-50' : ''}">Sun</span>
				</label>
			</div>

			<!-- Weekend Service toggle -->
			<div class="mt-3 border-t border-theme pt-3">
				<label class="flex items-start gap-2">
					<input
						type="checkbox"
						checked={weekendService}
						onchange={(e) => handleWeekendServiceChange(e.currentTarget.checked)}
						disabled={submitting}
						class="mt-0.5 {dayCheckboxClass}"
					/>
					<span class="flex flex-col">
						<span class="text-sm font-medium text-theme">Weekend Service</span>
						<span class="text-xs text-theme-muted">
							Single service visit on Friday that can be performed anytime Friday-Sunday
						</span>
					</span>
				</label>
			</div>
		</div>

		<!-- Schedule Exception -->
		<div>
			<label for="scheduleException" class="mb-1.5 block text-sm font-medium text-theme">
				Schedule Notes / Exceptions
			</label>
			<textarea
				id="scheduleException"
				bind:value={scheduleException}
				disabled={submitting}
				rows={3}
				placeholder="Any special requirements or exceptions..."
				class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme px-3 py-2 text-theme focus:border-primary-500 focus:ring-1 focus:ring-primary-500 disabled:cursor-not-allowed disabled:opacity-50"
			></textarea>
		</div>

		<!-- Actions -->
		<div class="flex items-center gap-3 pt-4">
			<button
				type="submit"
				disabled={submitting}
				class="flex-1 rounded-lg bg-primary-500 px-4 py-2 font-medium text-white transition-colors hover:bg-primary-600 disabled:cursor-not-allowed disabled:opacity-50"
			>
				{#if submitting}
					<span class="flex items-center justify-center gap-2">
						<IconSpinner class="h-4 w-4" />
						<span>{isEdit ? 'Saving...' : 'Creating...'}</span>
					</span>
				{:else}
					{isEdit ? 'Save Changes' : 'Add Schedule'}
				{/if}
			</button>
			<button
				type="button"
				onclick={handleCancel}
				disabled={submitting}
				class="rounded-lg border border-theme bg-theme px-4 py-2 font-medium text-theme transition-colors hover:bg-black/5 disabled:cursor-not-allowed disabled:opacity-50 dark:hover:bg-white/10"
			>
				Cancel
			</button>
		</div>
	</form>
</div>
