<script lang="ts">
	import ItemActions from '$lib/components/admin/ItemActions.svelte';
	import LaborSection from './LaborSection.svelte';
	import ScopeSection from './ScopeSection.svelte';
	import { IconChevronRight, IconEdit, IconTrash } from '$lib/components/icons';
	import { formatDate } from '$lib/utils/date';
	import { SvelteDate, type SvelteSet } from 'svelte/reactivity';
	import type { GetAccount$result, GetScopeTemplates$result } from '$houdini';
	import type { ScopeType, AreaType, TaskType } from '$lib/stores/scopeEditor.svelte';

	// Extract types from Houdini generated result
	type AddressType = NonNullable<GetAccount$result['account']>['addresses'][number];
	type LaborType = AddressType['labors'][number];
	type ScheduleType = AddressType['schedules'][number];
	type ScopeTemplateType = GetScopeTemplates$result['scopeTemplates'][number];

	interface Props {
		address: AddressType;
		isExpanded: boolean;
		showLaborHistory: boolean;
		showScheduleHistory: boolean;
		expandedScopes: SvelteSet<string>;
		expandedAreas: SvelteSet<string>;
		scopeTemplates: ScopeTemplateType[];
		scopeError?: string;
		onToggleExpanded: () => void;
		onEdit: () => void;
		onDelete: () => void;
		onAddSchedule: () => void;
		onEditSchedule: (schedule: ScheduleType) => void;
		onDeleteSchedule: (scheduleId: string) => void;
		onToggleScheduleHistory: () => void;
		onAddLabor: () => void;
		onEditLabor: (labor: LaborType) => void;
		onDeleteLabor: (laborId: string) => void;
		onToggleLaborHistory: () => void;
		onToggleScope: (scopeId: string) => void;
		onToggleArea: (areaId: string) => void;
		onAddScope: () => void;
		onAddScopeFromTemplate: (templateId: string) => void;
		onEditScope: (scope: ScopeType) => void;
		onDeleteScope: (scopeId: string) => void;
		onAddArea: (scopeId: string, nextOrder: number) => void;
		onEditArea: (scopeId: string, area: AreaType) => void;
		onDeleteArea: (areaId: string) => void;
		onAddTask: (areaId: string, nextOrder: number) => void;
		onEditTask: (areaId: string, task: TaskType) => void;
		onDeleteTask: (taskId: string) => void;
		onGenerateServices?: (addressId: string, scheduleId: string) => void;
		onClearScopeError?: () => void;
	}

	let {
		address,
		isExpanded,
		showLaborHistory,
		showScheduleHistory,
		expandedScopes,
		expandedAreas,
		scopeTemplates,
		scopeError = '',
		onToggleExpanded,
		onEdit,
		onDelete,
		onAddSchedule,
		onEditSchedule,
		onDeleteSchedule,
		onToggleScheduleHistory,
		onAddLabor,
		onEditLabor,
		onDeleteLabor,
		onToggleLaborHistory,
		onToggleScope,
		onToggleArea,
		onAddScope,
		onAddScopeFromTemplate,
		onEditScope,
		onDeleteScope,
		onAddArea,
		onEditArea,
		onDeleteArea,
		onAddTask,
		onEditTask,
		onDeleteTask,
		onGenerateServices,
		onClearScopeError
	}: Props = $props();

	// Separate current and past schedules
	let currentSchedules = $derived(
		address.schedules?.filter((s) => {
			if (!s.endDate) return true;
			const endDate = new Date(s.endDate);
			const today = new SvelteDate();
			today.setHours(0, 0, 0, 0);
			return endDate >= today;
		}) ?? []
	);

	let pastSchedules = $derived(
		address.schedules?.filter((s) => {
			if (!s.endDate) return false;
			const endDate = new Date(s.endDate);
			const today = new SvelteDate();
			today.setHours(0, 0, 0, 0);
			return endDate < today;
		}) ?? []
	);

	function getScheduleDays(schedule: ScheduleType): string[] {
		const days: string[] = [];
		if (schedule.mondayService) days.push('Mon');
		if (schedule.tuesdayService) days.push('Tue');
		if (schedule.wednesdayService) days.push('Wed');
		if (schedule.thursdayService) days.push('Thu');
		if (schedule.fridayService) days.push('Fri');
		if (schedule.saturdayService) days.push('Sat');
		if (schedule.sundayService) days.push('Sun');
		return days;
	}
</script>

<div
	class="rounded-lg border border-theme bg-theme {address.isPrimary
		? 'border-l-2 border-l-primary-500'
		: ''}"
>
	<!-- Address Header -->
	<div class="flex items-start justify-between gap-1 p-3">
		<button type="button" onclick={onToggleExpanded} class="min-w-0 flex-1 text-left">
			<span class="flex items-center gap-2">
				<IconChevronRight
					class="h-4 w-4 flex-shrink-0 text-theme-muted transition-transform {isExpanded
						? 'rotate-90'
						: ''}"
				/>
				<span class="font-medium text-theme"
					>{address.name ||
						(address.isPrimary ? 'Primary Service Address' : 'Service Address')}</span
				>
				{#if !address.isActive}
					<span class="badge-neutral">Inactive</span>
				{/if}
			</span>
			<span class="mt-0.5 block pl-6 text-sm text-theme-secondary">
				{address.streetAddress}, {address.city}, {address.state}
				{address.zipCode}
			</span>
		</button>
		<div class="flex shrink-0 items-center gap-1">
			<button
				type="button"
				onclick={onEdit}
				class="rounded p-1.5 text-gray-500 hover:bg-black/5 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/10 dark:hover:text-gray-300"
				aria-label="Edit address"
			>
				<IconEdit />
			</button>
			<button
				type="button"
				onclick={onDelete}
				class="rounded p-1.5 text-gray-500 hover:bg-red-50 hover:text-red-500 dark:text-gray-400 dark:hover:bg-red-900/20"
				aria-label="Delete address"
			>
				<IconTrash />
			</button>
		</div>
	</div>

	<!-- Address Expanded Content -->
	{#if isExpanded}
		<div class="border-t border-theme px-3 pb-3">
			<!-- Notes -->
			{#if address.notes}
				<p class="mt-3 text-sm text-theme-secondary italic">{address.notes}</p>
			{/if}

			<!-- Schedules for this address -->
			<div class="mt-3 border-t border-theme pt-3">
				<div class="mb-2 flex items-center justify-between">
					<p class="text-xs font-medium tracking-wide text-theme-muted uppercase">Schedules</p>
					<button
						type="button"
						onclick={onAddSchedule}
						class="text-xs font-medium text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300"
					>
						+ Add Schedule
					</button>
				</div>

				{#if currentSchedules.length > 0 || pastSchedules.length > 0}
					<div class="space-y-2">
						<!-- Current Schedules -->
						{#each currentSchedules as schedule (schedule.id)}
							{@const scheduleDays = getScheduleDays(schedule)}
							{@const isCurrentSchedule = !schedule.endDate}
							<div class="rounded border border-theme bg-theme-card p-2 text-sm">
								<div class="flex items-start justify-between gap-2">
									<div class="min-w-0 flex-1">
										<div class="flex flex-wrap items-center gap-2">
											<span class="font-medium text-theme"
												>{schedule.name || 'Unnamed Schedule'}</span
											>
											<span class="text-xs text-theme-muted">
												{#if isCurrentSchedule}
													As of {formatDate(schedule.startDate) || '—'}
												{:else}
													{formatDate(schedule.startDate) || '—'} - {formatDate(schedule.endDate)}
												{/if}
											</span>
											{#if isCurrentSchedule && onGenerateServices}
												<button
													type="button"
													onclick={() => onGenerateServices(address.id, schedule.id)}
													class="rounded bg-secondary-100 px-2 py-0.5 text-xs font-medium text-secondary-700 transition-colors hover:bg-secondary-200 dark:bg-secondary-900/40 dark:text-secondary-400 dark:hover:bg-secondary-900/60"
												>
													Generate
												</button>
											{/if}
										</div>
										<div class="mt-2 flex flex-wrap gap-1">
											{#if schedule.weekendService}
												<span
													class="rounded bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700 dark:bg-amber-900/40 dark:text-amber-400"
												>
													Weekend
												</span>
											{:else if scheduleDays.length > 0}
												{#each scheduleDays as day (day)}
													<span
														class="rounded bg-primary-100 px-2 py-0.5 text-xs font-medium text-primary-700 dark:bg-primary-900/40 dark:text-primary-400"
													>
														{day}
													</span>
												{/each}
											{:else}
												<span class="text-xs text-theme-muted">No days selected</span>
											{/if}
										</div>
										{#if schedule.scheduleException}
											<p class="mt-1 text-xs text-theme-muted italic">
												{schedule.scheduleException}
											</p>
										{/if}
									</div>
									<div class="shrink-0">
										<ItemActions
											size="sm"
											editLabel="Edit schedule"
											deleteLabel="Delete schedule"
											onEdit={() => onEditSchedule(schedule)}
											onDelete={() => onDeleteSchedule(schedule.id)}
										/>
									</div>
								</div>
							</div>
						{/each}

						<!-- Past Schedules (collapsed by default) -->
						{#if pastSchedules.length > 0}
							<div class="mt-2">
								<button
									type="button"
									onclick={onToggleScheduleHistory}
									class="text-xs font-medium text-theme-muted hover:text-theme-secondary"
								>
									{showScheduleHistory ? 'Hide' : 'Show'} past schedules ({pastSchedules.length})
								</button>

								{#if showScheduleHistory}
									<div class="mt-2 space-y-2">
										{#each pastSchedules as schedule (schedule.id)}
											{@const scheduleDays = getScheduleDays(schedule)}
											<div class="rounded border border-theme bg-theme-card p-2 text-sm opacity-60">
												<div class="flex items-start justify-between gap-2">
													<div class="min-w-0 flex-1">
														<div class="flex flex-wrap items-center gap-2">
															<span class="font-medium text-theme"
																>{schedule.name || 'Unnamed Schedule'}</span
															>
															<span class="text-xs text-theme-muted">
																{formatDate(schedule.startDate) || '—'} - {formatDate(
																	schedule.endDate
																)}
															</span>
														</div>
														<div class="mt-2 flex flex-wrap gap-1">
															{#if schedule.weekendService}
																<span
																	class="rounded bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700 dark:bg-amber-900/40 dark:text-amber-400"
																>
																	Weekend
																</span>
															{:else if scheduleDays.length > 0}
																{#each scheduleDays as day (day)}
																	<span
																		class="rounded bg-primary-100 px-2 py-0.5 text-xs font-medium text-primary-700 dark:bg-primary-900/40 dark:text-primary-400"
																	>
																		{day}
																	</span>
																{/each}
															{:else}
																<span class="text-xs text-theme-muted">No days selected</span>
															{/if}
														</div>
													</div>
													<div class="shrink-0">
														<ItemActions
															size="sm"
															editLabel="Edit schedule"
															deleteLabel="Delete schedule"
															onEdit={() => onEditSchedule(schedule)}
															onDelete={() => onDeleteSchedule(schedule.id)}
														/>
													</div>
												</div>
											</div>
										{/each}
									</div>
								{/if}
							</div>
						{/if}
					</div>
				{:else}
					<p class="text-sm text-theme-muted">No schedules configured</p>
				{/if}
			</div>

			<!-- Labor for this address -->
			<LaborSection
				labors={address.labors}
				showHistory={showLaborHistory}
				onAdd={onAddLabor}
				onEdit={onEditLabor}
				onDelete={onDeleteLabor}
				onToggleHistory={onToggleLaborHistory}
			/>

			<!-- Scopes for this address -->
			<ScopeSection
				scopes={address.scopes ?? []}
				{scopeTemplates}
				{expandedScopes}
				{expandedAreas}
				{scopeError}
				{onToggleScope}
				{onToggleArea}
				{onAddScope}
				{onAddScopeFromTemplate}
				{onEditScope}
				{onDeleteScope}
				{onAddArea}
				{onEditArea}
				{onDeleteArea}
				{onAddTask}
				{onEditTask}
				{onDeleteTask}
				onClearError={onClearScopeError}
			/>
		</div>
	{/if}
</div>
