<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import CustomerPageHeader from '$lib/components/customer/CustomerPageHeader.svelte';
	import ContactForm from '$lib/components/shared/ContactForm.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import { formatDate } from '$lib/utils/date';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { invalidateAll } from '$app/navigation';
	import { DeleteAccountContactStore } from '$houdini';
	import { getFrequencyLabel } from '$lib/stores/scopeEditor.svelte';
	import { SvelteSet } from 'svelte/reactivity';
	import type { PageData } from './$types';

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

	let account = $derived(data.account?.data?.account);
	let addresses = $derived(account?.addresses ?? []);
	let contacts = $derived(account?.contacts?.filter((c) => c.isActive) ?? []);

	// Contact editing state
	let editingContact = $state<(typeof contacts)[number] | null>(null);
	let deleteContactId = $state<string | null>(null);

	const deleteContactStore = new DeleteAccountContactStore();

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

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

	// Get active scope for an address
	function getActiveScope(address: (typeof addresses)[number]) {
		return address.scopes?.find((s) => s.isActive);
	}

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

	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
		});
	}

	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();
	}

	// Get upcoming services for this account
	let upcomingServices = $derived(
		addresses
			.flatMap((addr) => addr.services ?? [])
			.filter((s) => s.status === 'SCHEDULED' || s.status === 'IN_PROGRESS')
			.sort((a, b) => a.date.localeCompare(b.date))
			.slice(0, 5)
	);

	function getScheduleDays(schedule: {
		mondayService: boolean;
		tuesdayService: boolean;
		wednesdayService: boolean;
		thursdayService: boolean;
		fridayService: boolean;
		saturdayService: boolean;
		sundayService: boolean;
		weekendService: boolean;
	}): 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');
		if (schedule.weekendService && !schedule.saturdayService && !schedule.sundayService) {
			days.push('Weekends');
		}
		return days.length > 0 ? days.join(', ') : 'No scheduled days';
	}
</script>

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

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

<div class="py-8">
	<ContentContainer>
		<CustomerPageHeader
			title={account?.name ?? 'Account'}
			subtitle={account?.primaryAddress
				? `${account.primaryAddress.streetAddress}, ${account.primaryAddress.city}`
				: undefined}
			colorScheme="primary"
			backHref="/customer/accounts"
		/>

		{#if account}
			<div class="space-y-6">
				<!-- Addresses Section -->
				<div class="rounded-xl border border-theme bg-theme-card">
					<div class="border-b border-theme px-4 py-3">
						<h2 class="font-semibold text-theme">Service Locations</h2>
					</div>
					<div class="divide-theme divide-y">
						{#each addresses as address (address.id)}
							<div class="p-4">
								<div class="mb-2 flex items-start justify-between">
									<div>
										<h3 class="font-medium text-theme">
											{address.name || address.streetAddress}
											{#if address.isPrimary}
												<span
													class="ml-2 inline-flex items-center rounded-full bg-primary-100 px-2 py-0.5 text-xs font-medium text-primary-700 dark:bg-primary-900/30 dark:text-primary-400"
													>Primary</span
												>
											{/if}
										</h3>
										<p class="text-sm text-theme-secondary">
											{address.streetAddress}
										</p>
										<p class="text-sm text-theme-muted">
											{address.city}, {address.state}
											{address.zipCode}
										</p>
									</div>
								</div>

								<!-- Schedules for this address -->
								{#if address.schedules && address.schedules.length > 0}
									<div class="mt-3">
										<p class="mb-1 text-xs font-medium text-theme-muted uppercase">
											Service Schedule
										</p>
										{#each address.schedules as schedule (schedule.id)}
											<div
												class="mt-1 rounded-lg bg-black/5 p-2 text-sm text-theme-secondary dark:bg-white/5"
											>
												<span class="font-medium">{schedule.name || 'Regular Schedule'}:</span>
												{getScheduleDays(schedule)}
											</div>
										{/each}
									</div>
								{/if}

								<!-- Active Scope for this address -->
								{#if getActiveScope(address)}
									{@const activeScope = getActiveScope(address)}
									<div class="mt-4 border-t border-theme pt-4">
										<p class="mb-2 text-xs font-medium text-theme-muted uppercase">Service Scope</p>
										{#if activeScope?.description}
											<p class="mb-3 text-sm text-theme-secondary">{activeScope.description}</p>
										{/if}

										{#if activeScope?.areas && activeScope.areas.length > 0}
											<div class="space-y-2">
												{#each [...activeScope.areas].sort((a, b) => a.order - b.order) as area (area.id)}
													<div
														class="rounded-lg border border-theme bg-black/[0.02] dark:bg-white/[0.02]"
													>
														<button
															type="button"
															onclick={() => toggleArea(area.id)}
															class="flex w-full items-center justify-between px-3 py-2 text-left"
														>
															<span class="text-sm font-medium text-theme">{area.name}</span>
															<svg
																class="h-4 w-4 text-theme-muted transition-transform {expandedAreas.has(
																	area.id
																)
																	? 'rotate-180'
																	: ''}"
																style="fill: none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M19 9l-7 7-7-7"
																/>
															</svg>
														</button>

														{#if expandedAreas.has(area.id)}
															<div class="border-t border-theme px-3 py-2">
																{#if area.tasks && area.tasks.length > 0}
																	<ul class="space-y-1.5">
																		{#each [...area.tasks].sort((a, b) => a.order - b.order) as task (task.id)}
																			<li class="flex items-start justify-between gap-2 text-sm">
																				<span class="text-theme-secondary">{task.description}</span>
																				<span
																					class="shrink-0 rounded bg-black/5 px-1.5 py-0.5 text-xs text-theme-muted dark:bg-white/10"
																				>
																					{getFrequencyLabel(task.frequency)}
																				</span>
																			</li>
																		{/each}
																	</ul>
																{:else}
																	<p class="text-sm text-theme-muted">No tasks in this area.</p>
																{/if}
															</div>
														{/if}
													</div>
												{/each}
											</div>
										{:else}
											<p class="text-sm text-theme-muted">No areas defined in this scope.</p>
										{/if}
									</div>
								{/if}
							</div>
						{/each}
						{#if addresses.length === 0}
							<div class="px-4 py-8 text-center text-sm text-theme-muted">
								No addresses on file.
							</div>
						{/if}
					</div>
				</div>

				<!-- Contacts Section -->
				<div class="rounded-xl border border-theme bg-theme-card">
					<div class="flex items-center justify-between border-b border-theme px-4 py-3">
						<h2 class="font-semibold text-theme">Contacts</h2>
						<button
							type="button"
							onclick={showAddContactForm}
							class="rounded-lg bg-primary-500 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-primary-600"
						>
							Add Contact
						</button>
					</div>
					{#if contacts.length > 0}
						<div class="divide-theme divide-y">
							{#each contacts as contact (contact.id)}
								<div class="p-4">
									<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">{contact.fullName}</span>
												{#if contact.isPrimary}
													<span
														class="inline-flex items-center rounded-full bg-primary-100 px-2 py-0.5 text-xs font-medium text-primary-700 dark:bg-primary-900/30 dark:text-primary-400"
														>Primary</span
													>
												{/if}
											</div>
											{#if contact.email || contact.phone}
												<div class="mt-1 flex flex-col gap-0.5 sm:flex-row sm:flex-wrap sm:gap-x-4">
													{#if contact.email}
														<p class="text-sm text-theme-secondary">{contact.email}</p>
													{/if}
													{#if contact.phone}
														<p class="text-sm text-theme-muted">{contact.phone}</p>
													{/if}
												</div>
											{/if}
										</div>
										<div class="flex shrink-0 items-center gap-3">
											<button
												type="button"
												onclick={() => showEditContactForm(contact)}
												class="text-sm text-primary-600 hover:text-primary-700 hover:underline dark:text-primary-400 dark:hover:text-primary-300"
											>
												Edit
											</button>
											<button
												type="button"
												onclick={() => (deleteContactId = contact.id)}
												class="text-sm text-error-600 hover:text-error-700 hover:underline dark:text-error-400 dark:hover:text-error-300"
											>
												Delete
											</button>
										</div>
									</div>
								</div>
							{/each}
						</div>
					{:else}
						<div class="px-4 py-8 text-center text-sm text-theme-muted">
							No contacts on file. Add a contact to get started.
						</div>
					{/if}
				</div>

				<!-- Upcoming Services Section -->
				{#if upcomingServices.length > 0}
					<div class="rounded-xl border border-theme bg-theme-card">
						<div class="flex items-center justify-between border-b border-theme px-4 py-3">
							<h2 class="font-semibold text-theme">Upcoming Services</h2>
							<a
								href="/customer/schedule"
								class="text-sm text-accent-600 hover:underline dark:text-accent-400"
							>
								View all
							</a>
						</div>
						<div class="divide-theme divide-y">
							{#each upcomingServices as service (service.id)}
								<a
									href="/customer/schedule/service/{service.id}"
									class="flex items-center justify-between p-4 hover:bg-black/5 dark:hover:bg-white/5"
								>
									<div>
										<p class="text-sm font-medium text-theme">{formatDate(service.date)}</p>
										<p class="text-xs text-theme-muted">
											{service.status === 'SCHEDULED' ? 'Scheduled' : 'In Progress'}
										</p>
									</div>
									<span
										class="rounded px-2 py-1 text-xs {service.status === 'SCHEDULED'
											? 'bg-secondary-100 text-secondary-700 dark:bg-secondary-900/30 dark:text-secondary-400'
											: 'bg-warning-100 text-warning-700 dark:bg-warning-900/30 dark:text-warning-400'}"
									>
										{service.status === 'SCHEDULED' ? 'Scheduled' : 'In Progress'}
									</span>
								</a>
							{/each}
						</div>
					</div>
				{/if}
			</div>
		{:else}
			<div class="rounded-xl border border-theme bg-theme-card p-8 text-center">
				<p class="text-theme-muted">Account not found.</p>
			</div>
		{/if}
	</ContentContainer>
</div>

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