<script lang="ts">
	import type { PageData } from './$types';
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import AdminPageHeader from '$lib/components/admin/AdminPageHeader.svelte';
	import SectionHeader from '$lib/components/admin/SectionHeader.svelte';
	import AccountForm from '$lib/components/admin/accounts/AccountForm.svelte';
	import AddressForm from '$lib/components/shared/AddressForm.svelte';
	import ContactForm from '$lib/components/shared/ContactForm.svelte';
	import RevenueForm from '$lib/components/admin/accounts/RevenueForm.svelte';
	import LaborForm from '$lib/components/admin/accounts/LaborForm.svelte';
	import ScheduleForm from '$lib/components/admin/accounts/ScheduleForm.svelte';
	import ScopeForm from '$lib/components/admin/accounts/ScopeForm.svelte';
	import AreaForm from '$lib/components/admin/accounts/AreaForm.svelte';
	import TaskForm from '$lib/components/admin/accounts/TaskForm.svelte';
	import RevenueSection from '$lib/components/admin/accounts/RevenueSection.svelte';
	import AddressCard from '$lib/components/admin/accounts/AddressCard.svelte';
	import ContactListItem from '$lib/components/admin/accounts/ContactListItem.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import GenerateServicesModal from '$lib/components/admin/services/GenerateServicesModal.svelte';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { invalidateAll, goto } from '$app/navigation';
	import { SvelteSet } from 'svelte/reactivity';
	import {
		DeleteAccountStore,
		DeleteAccountContactStore,
		DeleteAccountAddressStore,
		DeleteRevenueStore,
		DeleteLaborStore,
		DeleteScheduleStore
	} from '$houdini';
	import { formatDate } from '$lib/utils/date';
	import { createScopeFromTemplate, deleteScope, deleteArea, deleteTask } from '$lib/utils/scopes';

	let { data }: { data: PageData } = $props();

	let account = $derived(data.account?.data?.account);
	let customers = $derived(data.customers?.data?.customers ?? []);
	let customerLookup = $derived(data.customerLookup);
	let addresses = $derived(account?.addresses ?? []);
	let contacts = $derived(account?.contacts ?? []);
	let revenues = $derived(account?.revenues ?? []);
	let scopeTemplates = $derived(data.scopeTemplates?.data?.scopeTemplates ?? []);
	let waveProducts = $derived(data.waveProducts ?? []);

	// Delete modal state
	let deleteModalOpen = $state(false);
	let deleteContactId = $state<string | null>(null);
	let deleteAddressId = $state<string | null>(null);
	let deleteRevenueId = $state<string | null>(null);
	let deleteLaborId = $state<string | null>(null);
	let deleteScheduleId = $state<string | null>(null);
	let deleteScopeId = $state<string | null>(null);
	let deleteAreaId = $state<string | null>(null);
	let deleteTaskId = $state<string | null>(null);
	let deleting = $state(false);

	// Edit state - store the item being edited so snippets can access it
	let editingAddress = $state<(typeof addresses)[number] | null>(null);
	let editingContact = $state<(typeof contacts)[number] | null>(null);
	let editingRevenue = $state<(typeof revenues)[number] | null>(null);
	let editingLabor = $state<{
		addressId: string;
		labor?: (typeof addresses)[number]['labors'][number];
	} | null>(null);

	// Schedule editing state
	type ScheduleType = (typeof addresses)[number]['schedules'][number];
	let editingSchedule = $state<{
		addressId: string;
		schedule?: ScheduleType;
	} | null>(null);

	// Scope editing state
	type ScopeType = (typeof addresses)[number]['scopes'][number];
	type AreaType = ScopeType['areas'][number];
	type TaskType = AreaType['tasks'][number];

	let editingScope = $state<{
		addressId: string;
		scope?: ScopeType;
		existingScopes: ScopeType[];
	} | null>(null);
	let editingArea = $state<{ scopeId: string; area?: AreaType; nextOrder: number } | null>(null);
	let editingTask = $state<{ areaId: string; task?: TaskType; nextOrder: number } | null>(null);

	// Scope error state (keyed by addressId)
	let scopeErrors = $state<Record<string, string>>({});

	// Track which addresses are expanded
	let expandedAddresses = new SvelteSet<string>();

	// Track which addresses have expanded labor history
	let expandedLaborHistoryAddresses = new SvelteSet<string>();

	// Track which addresses have expanded schedule history
	let expandedScheduleHistoryAddresses = new SvelteSet<string>();

	// Track which scopes and areas are expanded
	let expandedScopes = new SvelteSet<string>();
	let expandedAreas = new SvelteSet<string>();

	// Generate services modal state
	let showGenerateModal = $state(false);
	let generatePreselectedAddressId = $state<string | undefined>(undefined);
	let generatePreselectedScheduleId = $state<string | undefined>(undefined);

	function toggleAddressExpanded(addressId: string) {
		if (expandedAddresses.has(addressId)) {
			expandedAddresses.delete(addressId);
		} else {
			expandedAddresses.add(addressId);
		}
	}

	const deleteAccountStore = new DeleteAccountStore();
	const deleteContactStore = new DeleteAccountContactStore();
	const deleteAddressStore = new DeleteAccountAddressStore();
	const deleteRevenueStore = new DeleteRevenueStore();
	const deleteLaborStore = new DeleteLaborStore();
	const deleteScheduleStore = new DeleteScheduleStore();

	async function handleRefresh() {
		await invalidateAll();
	}

	function showEditForm() {
		if (!account) return;
		offCanvas.showRight({
			title: 'Edit Account',
			content: editFormContent
		});
	}

	function showAddAddressForm() {
		if (!account) return;
		editingAddress = null;
		offCanvas.showRight({
			title: 'Add Address',
			content: addressFormContent
		});
	}

	function showEditAddressForm(address: (typeof addresses)[number]) {
		if (!account) return;
		editingAddress = address;
		offCanvas.showRight({
			title: 'Edit Address',
			content: addressFormContent
		});
	}

	function showAddContactForm() {
		if (!account) return;
		editingContact = null;
		offCanvas.showRight({
			title: 'Add Contact',
			content: contactFormContent
		});
	}

	function showEditContactForm(contact: (typeof contacts)[number]) {
		if (!account) return;
		editingContact = contact;
		offCanvas.showRight({
			title: 'Edit Contact',
			content: contactFormContent
		});
	}

	function showAddRevenueForm() {
		if (!account) return;
		editingRevenue = null;
		offCanvas.showRight({
			title: 'Add Revenue',
			content: revenueFormContent
		});
	}

	function showEditRevenueForm(revenue: (typeof revenues)[number]) {
		if (!account) return;
		editingRevenue = revenue;
		offCanvas.showRight({
			title: 'Edit Revenue',
			content: revenueFormContent
		});
	}

	async function handleDeleteRevenue() {
		if (!deleteRevenueId) return;
		const res = await deleteRevenueStore.mutate({ id: deleteRevenueId });
		if (res.errors?.length) {
			throw new Error(res.errors.map((e) => e.message).join(', '));
		}
		deleteRevenueId = null;
		await invalidateAll();
	}

	function showAddLaborForm(addressId: string) {
		if (!account) return;
		editingLabor = { addressId };
		offCanvas.showRight({
			title: 'Add Labor Rate',
			content: laborFormContent
		});
	}

	function showEditLaborForm(
		addressId: string,
		labor: (typeof addresses)[number]['labors'][number]
	) {
		if (!account) return;
		editingLabor = { addressId, labor };
		offCanvas.showRight({
			title: 'Edit Labor Rate',
			content: laborFormContent
		});
	}

	async function handleDeleteLabor() {
		if (!deleteLaborId) return;
		const res = await deleteLaborStore.mutate({ id: deleteLaborId });
		if (res.errors?.length) {
			throw new Error(res.errors.map((e) => e.message).join(', '));
		}
		deleteLaborId = null;
		await invalidateAll();
	}

	function toggleLaborHistory(addressId: string) {
		if (expandedLaborHistoryAddresses.has(addressId)) {
			expandedLaborHistoryAddresses.delete(addressId);
		} else {
			expandedLaborHistoryAddresses.add(addressId);
		}
	}

	// Schedule functions
	function showAddScheduleForm(addressId: string) {
		if (!account) return;
		editingSchedule = { addressId };
		offCanvas.showRight({
			title: 'Add Schedule',
			content: scheduleFormContent
		});
	}

	function showEditScheduleForm(addressId: string, schedule: ScheduleType) {
		if (!account) return;
		editingSchedule = { addressId, schedule };
		offCanvas.showRight({
			title: 'Edit Schedule',
			content: scheduleFormContent
		});
	}

	async function handleDeleteSchedule() {
		if (!deleteScheduleId) return;
		const res = await deleteScheduleStore.mutate({ id: deleteScheduleId });
		if (res.errors?.length) {
			throw new Error(res.errors.map((e) => e.message).join(', '));
		}
		deleteScheduleId = null;
		await invalidateAll();
	}

	function toggleScheduleHistory(addressId: string) {
		if (expandedScheduleHistoryAddresses.has(addressId)) {
			expandedScheduleHistoryAddresses.delete(addressId);
		} else {
			expandedScheduleHistoryAddresses.add(addressId);
		}
	}

	// Scope functions
	function showAddScopeForm(addressId: string) {
		if (!account) return;
		const address = addresses.find((a) => a.id === addressId);
		const existingScopes = address?.scopes ?? [];
		editingScope = { addressId, existingScopes };
		offCanvas.showRight({
			title: 'Add Scope',
			content: scopeFormContent
		});
	}

	function showEditScopeForm(addressId: string, scope: ScopeType) {
		if (!account) return;
		const address = addresses.find((a) => a.id === addressId);
		const existingScopes = address?.scopes ?? [];
		editingScope = { addressId, scope, existingScopes };
		offCanvas.showRight({
			title: 'Edit Scope',
			content: scopeFormContent
		});
	}

	async function handleAddScopeFromTemplate(addressId: string, templateId: string) {
		if (!account) return;
		// Clear any previous error for this address
		scopeErrors = { ...scopeErrors, [addressId]: '' };
		try {
			await createScopeFromTemplate({
				templateId,
				accountId: account.id,
				accountAddressId: addressId,
				isActive: true
			});
			await invalidateAll();
		} catch (err) {
			console.error('Failed to create scope from template:', err);
			const errorMessage = err instanceof Error ? err.message : String(err);
			if (errorMessage.includes('unique_active_scope_per_address')) {
				scopeErrors = {
					...scopeErrors,
					[addressId]: 'This location already has an active scope. Deactivate the existing scope before adding a new one.'
				};
			} else {
				scopeErrors = {
					...scopeErrors,
					[addressId]: 'Failed to create scope. Please try again.'
				};
			}
		}
	}

	async function handleDeleteScope() {
		if (!deleteScopeId) return;
		try {
			await deleteScope(deleteScopeId);
			deleteScopeId = null;
			await invalidateAll();
		} catch (err) {
			console.error('Failed to delete scope:', err);
			throw err;
		}
	}

	function toggleScopeExpanded(scopeId: string) {
		if (expandedScopes.has(scopeId)) {
			expandedScopes.delete(scopeId);
		} else {
			expandedScopes.add(scopeId);
		}
	}

	function toggleAreaExpanded(areaId: string) {
		if (expandedAreas.has(areaId)) {
			expandedAreas.delete(areaId);
		} else {
			expandedAreas.add(areaId);
		}
	}

	// Area functions
	function showAddAreaForm(scopeId: string, nextOrder: number) {
		editingArea = { scopeId, nextOrder };
		offCanvas.showRight({
			title: 'Add Area',
			content: areaFormContent
		});
	}

	function showEditAreaForm(scopeId: string, area: AreaType) {
		editingArea = { scopeId, area, nextOrder: area.order };
		offCanvas.showRight({
			title: 'Edit Area',
			content: areaFormContent
		});
	}

	async function handleDeleteArea() {
		if (!deleteAreaId) return;
		try {
			await deleteArea(deleteAreaId);
			deleteAreaId = null;
			await invalidateAll();
		} catch (err) {
			console.error('Failed to delete area:', err);
			throw err;
		}
	}

	// Task functions
	function showAddTaskForm(areaId: string, nextOrder: number) {
		editingTask = { areaId, nextOrder };
		offCanvas.showRight({
			title: 'Add Task',
			content: taskFormContent
		});
	}

	function showEditTaskForm(areaId: string, task: TaskType) {
		editingTask = { areaId, task, nextOrder: task.order };
		offCanvas.showRight({
			title: 'Edit Task',
			content: taskFormContent
		});
	}

	async function handleDeleteTask() {
		if (!deleteTaskId) return;
		try {
			await deleteTask(deleteTaskId);
			deleteTaskId = null;
			await invalidateAll();
		} catch (err) {
			console.error('Failed to delete task:', err);
			throw err;
		}
	}

	async function handleDeleteAccount() {
		if (!account) return;
		deleting = true;
		try {
			const res = await deleteAccountStore.mutate({ id: account.id });
			if (res.errors?.length) {
				throw new Error(res.errors.map((e) => e.message).join(', '));
			}
			await goto('/admin/accounts');
		} finally {
			deleting = false;
		}
	}

	async function handleDeleteContact() {
		if (!deleteContactId) return;
		const res = await deleteContactStore.mutate({ id: deleteContactId });
		if (res.errors?.length) {
			throw new Error(res.errors.map((e) => e.message).join(', '));
		}
		deleteContactId = null;
		await invalidateAll();
	}

	async function handleDeleteAddress() {
		if (!deleteAddressId) return;
		const res = await deleteAddressStore.mutate({ id: deleteAddressId });
		if (res.errors?.length) {
			throw new Error(res.errors.map((e) => e.message).join(', '));
		}
		deleteAddressId = null;
		await invalidateAll();
	}

	function getCustomerName(customerId: string | null | undefined): string {
		if (!customerId || !customerLookup) return '—';
		const customer = customerLookup.get(customerId);
		return customer?.customerName ?? '—';
	}

	function openGenerateServicesModal(addressId: string, scheduleId: string) {
		generatePreselectedAddressId = addressId;
		generatePreselectedScheduleId = scheduleId;
		showGenerateModal = true;
	}

	function closeGenerateServicesModal() {
		showGenerateModal = false;
		generatePreselectedAddressId = undefined;
		generatePreselectedScheduleId = undefined;
	}
</script>

{#snippet editFormContent()}
	{#if account}
		<AccountForm {account} {customers} onSuccess={handleRefresh} />
	{/if}
{/snippet}

{#snippet addressFormContent()}
	{#if account}
		<AddressForm
			entityType="account"
			entityId={account.id}
			address={editingAddress ?? undefined}
			onSuccess={handleRefresh}
		/>
	{/if}
{/snippet}

{#snippet contactFormContent()}
	{#if account}
		<ContactForm
			entityType="account"
			entityId={account.id}
			contact={editingContact ?? undefined}
			onSuccess={handleRefresh}
		/>
	{/if}
{/snippet}

{#snippet revenueFormContent()}
	{#if account}
		<RevenueForm
			accountId={account.id}
			revenue={editingRevenue ?? undefined}
			{waveProducts}
			onSuccess={handleRefresh}
		/>
	{/if}
{/snippet}

{#snippet laborFormContent()}
	{#if editingLabor}
		<LaborForm
			accountAddressId={editingLabor.addressId}
			labor={editingLabor.labor}
			onSuccess={handleRefresh}
		/>
	{/if}
{/snippet}

{#snippet scheduleFormContent()}
	{#if editingSchedule}
		<ScheduleForm
			accountAddressId={editingSchedule.addressId}
			schedule={editingSchedule.schedule}
			onSuccess={handleRefresh}
		/>
	{/if}
{/snippet}

{#snippet scopeFormContent()}
	{#if editingScope && account}
		<ScopeForm
			accountId={account.id}
			accountAddressId={editingScope.addressId}
			scope={editingScope.scope}
			existingScopes={editingScope.existingScopes}
			onSuccess={handleRefresh}
		/>
	{/if}
{/snippet}

{#snippet areaFormContent()}
	{#if editingArea}
		<AreaForm
			scopeId={editingArea.scopeId}
			area={editingArea.area}
			nextOrder={editingArea.nextOrder}
			onSuccess={handleRefresh}
		/>
	{/if}
{/snippet}

{#snippet taskFormContent()}
	{#if editingTask}
		<TaskForm
			areaId={editingTask.areaId}
			task={editingTask.task}
			nextOrder={editingTask.nextOrder}
			onSuccess={handleRefresh}
		/>
	{/if}
{/snippet}

<svelte:head>
	<title>{account?.name ?? 'Account'} - Accounts - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		{#if account}
			<AdminPageHeader
				title={account.name}
				subtitle="Account Details"
				backHref="/admin/accounts"
				invalidateOnBack
			/>

			<div class="space-y-8">
				<!-- Account Info Card -->
				<div class="card-padded">
					<SectionHeader
						title="Account Information"
						buttonText="Edit"
						buttonIcon="none"
						onButtonClick={showEditForm}
					/>

					<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
						<div>
							<p class="detail-label">Name</p>
							<p class="text-theme">{account.name}</p>
						</div>
						<div>
							<p class="detail-label">Status</p>
							<span
								class={account.status === 'ACTIVE'
									? 'badge-success'
									: account.status === 'PENDING'
										? 'badge-warning'
										: 'badge-neutral'}
							>
								{account.status}
							</span>
						</div>
						<div>
							<p class="detail-label">Customer</p>
							<p class="text-theme">{getCustomerName(account.customerId)}</p>
						</div>
						<div>
							<p class="detail-label">Start Date</p>
							<p class="text-theme">{formatDate(account.startDate) || '—'}</p>
						</div>
						<div>
							<p class="detail-label">End Date</p>
							<p class="text-theme">{formatDate(account.endDate) || '—'}</p>
						</div>
					</div>
				</div>

				<!-- Revenue Section -->
				<RevenueSection
					{revenues}
					{waveProducts}
					onAdd={showAddRevenueForm}
					onEdit={showEditRevenueForm}
					onDelete={(id) => (deleteRevenueId = id)}
				/>

				<!-- Addresses Section -->
				<div class="card-padded">
					<SectionHeader title="Addresses" buttonText="Add" onButtonClick={showAddAddressForm} />

					{#if addresses.length > 0}
						<div class="space-y-4">
							{#each addresses as address (address.id)}
								<AddressCard
									{address}
									isExpanded={expandedAddresses.has(address.id)}
									showLaborHistory={expandedLaborHistoryAddresses.has(address.id)}
									showScheduleHistory={expandedScheduleHistoryAddresses.has(address.id)}
									{expandedScopes}
									{expandedAreas}
									{scopeTemplates}
									scopeError={scopeErrors[address.id] || ''}
									onToggleExpanded={() => toggleAddressExpanded(address.id)}
									onEdit={() => showEditAddressForm(address)}
									onDelete={() => (deleteAddressId = address.id)}
									onAddSchedule={() => showAddScheduleForm(address.id)}
									onEditSchedule={(schedule) => showEditScheduleForm(address.id, schedule)}
									onDeleteSchedule={(scheduleId) => (deleteScheduleId = scheduleId)}
									onToggleScheduleHistory={() => toggleScheduleHistory(address.id)}
									onAddLabor={() => showAddLaborForm(address.id)}
									onEditLabor={(labor) => showEditLaborForm(address.id, labor)}
									onDeleteLabor={(laborId) => (deleteLaborId = laborId)}
									onToggleLaborHistory={() => toggleLaborHistory(address.id)}
									onToggleScope={toggleScopeExpanded}
									onToggleArea={toggleAreaExpanded}
									onAddScope={() => showAddScopeForm(address.id)}
									onAddScopeFromTemplate={(templateId) =>
										handleAddScopeFromTemplate(address.id, templateId)}
									onEditScope={(scope) => showEditScopeForm(address.id, scope)}
									onDeleteScope={(scopeId) => (deleteScopeId = scopeId)}
									onAddArea={(scopeId, nextOrder) => showAddAreaForm(scopeId, nextOrder)}
									onEditArea={(scopeId, area) => showEditAreaForm(scopeId, area)}
									onDeleteArea={(areaId) => (deleteAreaId = areaId)}
									onAddTask={(areaId, nextOrder) => showAddTaskForm(areaId, nextOrder)}
									onEditTask={(areaId, task) => showEditTaskForm(areaId, task)}
									onDeleteTask={(taskId) => (deleteTaskId = taskId)}
									onGenerateServices={openGenerateServicesModal}
									onClearScopeError={() => (scopeErrors = { ...scopeErrors, [address.id]: '' })}
								/>
							{/each}
						</div>
					{:else}
						<p class="text-center text-theme-muted">No addresses added yet.</p>
					{/if}
				</div>

				<!-- Contacts Section -->
				<div class="card-padded">
					<SectionHeader title="Contacts" buttonText="Add" onButtonClick={showAddContactForm} />

					{#if contacts.length > 0}
						<div class="space-y-3">
							{#each contacts as contact (contact.id)}
								<ContactListItem
									{contact}
									onEdit={() => showEditContactForm(contact)}
									onDelete={() => (deleteContactId = contact.id)}
								/>
							{/each}
						</div>
					{:else}
						<p class="text-center text-theme-muted">No contacts added yet.</p>
					{/if}
				</div>

				<!-- Danger Zone -->
				<div class="danger-zone">
					<h2 class="danger-zone-title">Danger Zone</h2>
					<p class="danger-zone-text">
						Deleting this account will remove all associated addresses, contacts, and schedules.
						This action cannot be undone.
					</p>
					<button type="button" onclick={() => (deleteModalOpen = true)} class="btn-danger">
						Delete Account
					</button>
				</div>
			</div>
		{:else}
			<div class="empty-state">
				<svg class="empty-state-icon" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
					/>
				</svg>
				<h2 class="empty-state-title">Account not found</h2>
				<p class="empty-state-text">
					The account you're looking for doesn't exist or has been deleted.
				</p>
				<a href="/admin/accounts" class="mt-4 btn-primary">Back to Accounts</a>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Delete Account Modal -->
<DeleteConfirmModal
	bind:open={deleteModalOpen}
	title="Delete Account"
	message="Are you sure you want to delete this account? All addresses, contacts, and schedules will be removed. This action cannot be undone."
	loading={deleting}
	onconfirm={handleDeleteAccount}
	oncancel={() => (deleteModalOpen = false)}
/>

<!-- Delete Contact Modal -->
<DeleteConfirmModal
	open={!!deleteContactId}
	title="Delete Contact"
	message="Are you sure you want to delete this contact?"
	onconfirm={handleDeleteContact}
	oncancel={() => (deleteContactId = null)}
/>

<!-- Delete Address Modal -->
<DeleteConfirmModal
	open={!!deleteAddressId}
	title="Delete Address"
	message="Are you sure you want to delete this address? All associated schedules will also be removed."
	onconfirm={handleDeleteAddress}
	oncancel={() => (deleteAddressId = null)}
/>

<!-- Delete Revenue Modal -->
<DeleteConfirmModal
	open={!!deleteRevenueId}
	title="Delete Revenue"
	message="Are you sure you want to delete this revenue record?"
	onconfirm={handleDeleteRevenue}
	oncancel={() => (deleteRevenueId = null)}
/>

<!-- Delete Labor Modal -->
<DeleteConfirmModal
	open={!!deleteLaborId}
	title="Delete Labor Rate"
	message="Are you sure you want to delete this labor rate record?"
	onconfirm={handleDeleteLabor}
	oncancel={() => (deleteLaborId = null)}
/>

<!-- Delete Schedule Modal -->
<DeleteConfirmModal
	open={!!deleteScheduleId}
	title="Delete Schedule"
	message="Are you sure you want to delete this schedule?"
	onconfirm={handleDeleteSchedule}
	oncancel={() => (deleteScheduleId = null)}
/>

<!-- Delete Scope Modal -->
<DeleteConfirmModal
	open={!!deleteScopeId}
	title="Delete Scope"
	message="Are you sure you want to delete this scope? If this scope has been used in service sessions, it will be deactivated instead to preserve historical data."
	onconfirm={handleDeleteScope}
	oncancel={() => (deleteScopeId = null)}
/>

<!-- Delete Area Modal -->
<DeleteConfirmModal
	open={!!deleteAreaId}
	title="Delete Area"
	message="Are you sure you want to delete this area? All associated tasks will also be removed."
	onconfirm={handleDeleteArea}
	oncancel={() => (deleteAreaId = null)}
/>

<!-- Delete Task Modal -->
<DeleteConfirmModal
	open={!!deleteTaskId}
	title="Delete Task"
	message="Are you sure you want to delete this task?"
	onconfirm={handleDeleteTask}
	oncancel={() => (deleteTaskId = null)}
/>

<!-- Generate Services Modal -->
{#if account}
	<GenerateServicesModal
		bind:open={showGenerateModal}
		accounts={[
			{
				id: account.id,
				name: account.name,
				addresses: addresses.map((addr) => ({
					id: addr.id,
					name: addr.name,
					streetAddress: addr.streetAddress,
					city: addr.city,
					state: addr.state,
					zipCode: addr.zipCode,
					isActive: addr.isActive,
					schedules: addr.schedules
				}))
			}
		]}
		preselectedAddressId={generatePreselectedAddressId}
		preselectedScheduleId={generatePreselectedScheduleId}
		onClose={closeGenerateServicesModal}
		onSuccess={async () => {
			await invalidateAll();
		}}
	/>
{/if}
