<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 { IconEdit, IconTrash } from '$lib/components/icons';
	import CustomerForm from '$lib/components/admin/customers/CustomerForm.svelte';
	import ContactForm from '$lib/components/shared/ContactForm.svelte';
	import AddressForm from '$lib/components/shared/AddressForm.svelte';
	import DeleteConfirmModal from '$lib/components/admin/DeleteConfirmModal.svelte';
	import WaveCustomerLinkForm from '$lib/components/admin/customers/WaveCustomerLinkForm.svelte';
	import WaveIntegrationSection from '$lib/components/admin/customers/WaveIntegrationSection.svelte';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { invalidateAll, goto } from '$app/navigation';
	import { formatDate } from '$lib/utils/date';
	import { fromGlobalId } from '$lib/utils/relay';
	import {
		DeleteCustomerStore,
		DeleteCustomerContactStore,
		DeleteCustomerAddressStore
	} from '$houdini';

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

	let customer = $derived(data.customer?.data?.customer);
	let contacts = $derived(customer?.contacts ?? []);
	let addresses = $derived(customer?.addresses ?? []);
	let accounts = $derived(customer?.accounts ?? []);
	let waveCustomers = $derived(data.waveCustomers ?? []);

	// Find the linked Wave customer by matching decoded IDs
	let linkedWaveCustomer = $derived.by(() => {
		if (!customer?.waveCustomerId) return null;
		return waveCustomers.find((wc) => fromGlobalId(wc.id) === customer.waveCustomerId) ?? null;
	});

	// Delete modal state
	let deleteModalOpen = $state(false);
	let deleteContactId = $state<string | null>(null);
	let deleteAddressId = $state<string | null>(null);
	let deleting = $state(false);

	// Edit state - store the item being edited so snippets can access it
	let editingContact = $state<(typeof contacts)[number] | null>(null);
	let editingAddress = $state<(typeof addresses)[number] | null>(null);

	const deleteCustomerStore = new DeleteCustomerStore();
	const deleteContactStore = new DeleteCustomerContactStore();
	const deleteAddressStore = new DeleteCustomerAddressStore();

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

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

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

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

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

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

	async function handleDeleteCustomer() {
		if (!customer) return;
		deleting = true;
		try {
			const res = await deleteCustomerStore.mutate({ id: customer.id });
			if (res.errors?.length) {
				throw new Error(res.errors.map((e) => e.message).join(', '));
			}
			await goto('/admin/customers');
		} 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 showWaveLinkForm() {
		if (!customer) return;
		offCanvas.showRight({
			title: 'Link Wave Customer',
			content: waveLinkFormContent
		});
	}
</script>

{#snippet editFormContent()}
	{#if customer}
		<CustomerForm {customer} onSuccess={handleRefresh} />
	{/if}
{/snippet}

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

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

{#snippet waveLinkFormContent()}
	{#if customer}
		<WaveCustomerLinkForm
			customerId={customer.id}
			currentWaveCustomerId={customer.waveCustomerId}
			{waveCustomers}
			onSuccess={handleRefresh}
		/>
	{/if}
{/snippet}

<svelte:head>
	<title>{customer?.name ?? 'Customer'} - Customers - Admin - Nexus</title>
</svelte:head>

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

			<div class="space-y-8">
				<!-- Customer Info Card -->
				<div class="card-padded">
					<SectionHeader
						title="Customer 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">{customer.name}</p>
						</div>
						<div>
							<p class="detail-label">Status</p>
							<span
								class={customer.status === 'ACTIVE'
									? 'badge-success'
									: customer.status === 'PENDING'
										? 'badge-warning'
										: 'badge-neutral'}
							>
								{customer.status}
							</span>
						</div>
						<div>
							<p class="detail-label">Billing Email</p>
							<p class="text-theme">{customer.billingEmail || '—'}</p>
						</div>
						<div>
							<p class="detail-label">Billing Terms</p>
							<p class="text-theme">{customer.billingTerms || '—'}</p>
						</div>
						<div>
							<p class="detail-label">Start Date</p>
							<p class="text-theme">{formatDate(customer.startDate)}</p>
						</div>
						<div>
							<p class="detail-label">End Date</p>
							<p class="text-theme">{formatDate(customer.endDate)}</p>
						</div>
					</div>
				</div>

				<!-- Wave Integration Section -->
				<WaveIntegrationSection
					waveCustomerId={customer.waveCustomerId}
					{linkedWaveCustomer}
					onLink={showWaveLinkForm}
				/>

				<!-- 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)}
								<div
									class="flex items-center justify-between rounded-lg border border-theme bg-theme p-3"
								>
									<div class="min-w-0 flex-1">
										<div class="flex items-center gap-2">
											<span class="font-medium text-theme">{contact.fullName}</span>
											{#if contact.isPrimary}
												<span class="badge-primary">Primary</span>
											{/if}
										</div>
										{#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>
									<div class="flex shrink-0 items-center gap-1">
										<button
											type="button"
											onclick={() => showEditContactForm(contact)}
											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 contact"
										>
											<IconEdit />
										</button>
										<button
											type="button"
											onclick={() => (deleteContactId = contact.id)}
											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 contact"
										>
											<IconTrash />
										</button>
									</div>
								</div>
							{/each}
						</div>
					{:else}
						<p class="text-center text-theme-muted">No contacts added yet.</p>
					{/if}
				</div>

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

					{#if addresses.length > 0}
						<div class="space-y-3">
							{#each addresses as address (address.id)}
								<div
									class="flex items-center justify-between rounded-lg border border-theme bg-theme p-3"
								>
									<div class="min-w-0 flex-1">
										<div class="flex items-center gap-2">
											<span class="font-medium text-theme">{address.streetAddress}</span>
											{#if address.isPrimary}
												<span class="badge-primary">Primary</span>
											{/if}
											<span class="badge-neutral">
												{address.addressType}
											</span>
										</div>
										<p class="text-sm text-theme-secondary">
											{address.city}, {address.state}
											{address.zipCode}
										</p>
									</div>
									<div class="flex shrink-0 items-center gap-1">
										<button
											type="button"
											onclick={() => showEditAddressForm(address)}
											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={() => (deleteAddressId = address.id)}
											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>
							{/each}
						</div>
					{:else}
						<p class="text-center text-theme-muted">No addresses added yet.</p>
					{/if}
				</div>

				<!-- Linked Accounts Section -->
				{#if accounts.length > 0}
					<div class="card-padded">
						<h2 class="mb-4 text-lg font-semibold text-theme">Linked Accounts</h2>
						<div class="space-y-2">
							{#each accounts as account (account.id)}
								<a
									href="/admin/accounts/{account.id}"
									class="flex items-center justify-between rounded-lg border border-theme bg-theme p-3 transition-colors hover:bg-black/5 dark:hover:bg-white/5"
								>
									<span class="font-medium text-primary-600 dark:text-primary-400"
										>{account.name}</span
									>
									<svg
										class="h-4 w-4 text-theme-muted"
										style="fill: none"
										stroke="currentColor"
										viewBox="0 0 24 24"
									>
										<path
											stroke-linecap="round"
											stroke-linejoin="round"
											stroke-width="2"
											d="M9 5l7 7-7 7"
										/>
									</svg>
								</a>
							{/each}
						</div>
					</div>
				{/if}

				<!-- Danger Zone -->
				<div class="danger-zone">
					<h2 class="danger-zone-title">Danger Zone</h2>
					<p class="danger-zone-text">
						Deleting this customer will remove all associated contacts and addresses. This action
						cannot be undone.
					</p>
					<button type="button" onclick={() => (deleteModalOpen = true)} class="btn-danger">
						Delete Customer
					</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">Customer not found</h2>
				<p class="empty-state-text">
					The customer you're looking for doesn't exist or has been deleted.
				</p>
				<a href="/admin/customers" class="mt-4 btn-primary">Back to Customers</a>
			</div>
		{/if}
	</ContentContainer>
</div>

<!-- Delete Customer Modal -->
<DeleteConfirmModal
	bind:open={deleteModalOpen}
	title="Delete Customer"
	message="Are you sure you want to delete this customer? All contacts and addresses will be removed. This action cannot be undone."
	loading={deleting}
	onconfirm={handleDeleteCustomer}
	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?"
	onconfirm={handleDeleteAddress}
	oncancel={() => (deleteAddressId = null)}
/>
