<script lang="ts">
	import type { PageData } from './$types';
	import { invalidateAll } from '$app/navigation';
	import { ContentContainer } from '$lib/components/layout';
	import { PageHeader, SectionHeader } from '$lib/components/admin';
	import { IconEdit, IconTrash, IconChevronRight, IconPlus } from '$lib/components/icons';
	import { formatDate } from '$lib/utils/date';
	import { DeleteModal } from '$lib/components/modals';
	import { FormDrawer } from '$lib/components/drawers';
	import { ContactForm, CustomerForm } from '$lib/components/forms';
	import { client } from '$lib/graphql/client';
	import { DELETE_CUSTOMER, DELETE_CUSTOMER_CONTACT } from '$lib/graphql/mutations/customer';
	import type { CustomerContact } from '$lib/graphql/queries/customer';

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

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

	// Split addresses into active (current billing) and inactive (history)
	let activeAddress = $derived(addresses.find((a) => a.isActive) ?? null);
	let inactiveAddresses = $derived(addresses.filter((a) => !a.isActive));

	// Drawer state
	let drawerOpen = $state(false);
	type DrawerMode =
		| { type: 'customer'; mode: 'edit' }
		| { type: 'contact'; mode: 'add' }
		| { type: 'contact'; mode: 'edit'; data: CustomerContact };
	let drawerMode = $state<DrawerMode | null>(null);

	// Delete modal state
	let deleteModalOpen = $state(false);
	let deleteTarget = $state<{
		type: 'customer' | 'contact';
		id: string;
		name: string;
	} | null>(null);
	let deleteLoading = $state(false);

	function getStatusBadgeClass(status: string): string {
		switch (status) {
			case 'ACTIVE':
				return 'badge-success';
			case 'INACTIVE':
				return 'badge-neutral';
			case 'PENDING':
				return 'badge-warning';
			default:
				return 'badge-neutral';
		}
	}

	// Drawer handlers
	function handleEditCustomer() {
		drawerMode = { type: 'customer', mode: 'edit' };
		drawerOpen = true;
	}

	function handleAddContact() {
		drawerMode = { type: 'contact', mode: 'add' };
		drawerOpen = true;
	}

	function handleEditContact(contact: CustomerContact) {
		drawerMode = { type: 'contact', mode: 'edit', data: contact };
		drawerOpen = true;
	}

	function closeDrawer() {
		drawerOpen = false;
		drawerMode = null;
	}

	async function handleFormSuccess() {
		closeDrawer();
		await invalidateAll();
	}

	// Delete handlers
	function handleDeleteContact(contact: CustomerContact) {
		deleteTarget = {
			type: 'contact',
			id: contact.id,
			name: `${contact.firstName} ${contact.lastName}`
		};
		deleteModalOpen = true;
	}

	function handleDeleteCustomer() {
		if (!customer) return;
		deleteTarget = {
			type: 'customer',
			id: customer.id,
			name: customer.name
		};
		deleteModalOpen = true;
	}

	function closeDeleteModal() {
		deleteModalOpen = false;
		deleteTarget = null;
	}

	async function confirmDelete() {
		if (!deleteTarget) return;

		deleteLoading = true;
		try {
			if (deleteTarget.type === 'contact') {
				await client.mutate({
					mutation: DELETE_CUSTOMER_CONTACT,
					variables: { id: deleteTarget.id }
				});
			} else if (deleteTarget.type === 'customer') {
				await client.mutate({
					mutation: DELETE_CUSTOMER,
					variables: { id: deleteTarget.id }
				});
				// Redirect to customers list after deleting
				window.location.href = '/admin/customers';
				return;
			}

			closeDeleteModal();
			await invalidateAll();
		} catch (err) {
			console.error('Delete failed:', err);
		} finally {
			deleteLoading = false;
		}
	}

	function handleAddAccount() {
		// TODO: Implement account linking
		console.log('Add account - not yet implemented');
	}

	// Derived drawer title
	let drawerTitle = $derived(() => {
		if (!drawerMode) return '';
		const action = drawerMode.mode === 'add' ? 'Add' : 'Edit';
		const entity = drawerMode.type.charAt(0).toUpperCase() + drawerMode.type.slice(1);
		return `${action} ${entity}`;
	});
</script>

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

<div class="py-8">
	<ContentContainer maxWidth="4xl">
		{#if customer}
			<PageHeader
				title={customer.name}
				colorScheme="accent3"
				backHref="/admin/customers"
				invalidateOnBack
			>
				<span class={getStatusBadgeClass(customer.status)}>{customer.status}</span>
			</PageHeader>

			<div class="space-y-6">
				<!-- Billing Information -->
				<section
					class="overflow-hidden rounded-xl border border-accent3-500/20 bg-theme-card shadow-theme-md"
				>
					<div
						class="border-b border-accent3-500/20 bg-linear-to-r from-accent3-500/10 to-transparent px-5 py-3"
					>
						<SectionHeader
							title="Billing Info"
							buttonText="Edit"
							buttonIcon="edit"
							onButtonClick={handleEditCustomer}
						/>
					</div>
					<div class="grid grid-cols-1 gap-6 px-5 py-5 sm:grid-cols-2">
						<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">Billing Address</p>
							{#if activeAddress}
								<p class="text-theme">{activeAddress.streetAddress}</p>
								<p class="text-theme-secondary">
									{activeAddress.city}, {activeAddress.state}
									{activeAddress.zipCode}
								</p>
							{:else}
								<p class="text-theme-muted">Not set</p>
							{/if}
						</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>
						{#if customer.waveCustomerId}
							<div>
								<p class="detail-label">Wave Customer</p>
								<div class="flex items-center gap-2">
									<span class="badge-success">Linked</span>
									{#if customer.waveCustomerName}
										<span class="text-theme">{customer.waveCustomerName}</span>
									{:else}
										<span class="text-sm text-theme-muted">ID: {customer.waveCustomerId}</span>
									{/if}
								</div>
							</div>
						{/if}
					</div>
				</section>

				<!-- Contacts -->
				<section
					class="overflow-hidden rounded-xl border border-accent3-500/20 bg-theme-card shadow-theme-md"
				>
					<div
						class="border-b border-accent3-500/20 bg-linear-to-r from-accent3-500/10 to-transparent px-5 py-3"
					>
						<SectionHeader title="Contacts" buttonText="Add" onButtonClick={handleAddContact} />
					</div>
					<div class="px-5 py-5">
						{#if contacts.length > 0}
							<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
								{#each contacts as contact (contact.id)}
									<div
										class="group/card bg-theme-secondary/50 relative rounded-lg border border-theme p-3 transition-colors hover:bg-theme-secondary"
									>
										<div class="absolute top-2 right-2 flex items-center gap-0.5">
											<button
												type="button"
												onclick={() => handleEditContact(contact)}
												class="btn-icon-sm text-theme-muted hover:text-theme"
												aria-label="Edit contact"
											>
												<IconEdit />
											</button>
											<button
												type="button"
												onclick={() => handleDeleteContact(contact)}
												class="btn-icon-sm btn-delete-hover text-theme-muted"
												aria-label="Delete contact"
											>
												<IconTrash />
											</button>
										</div>
										<div class="pr-14">
											<span class="font-medium text-theme">
												{contact.firstName}
												{contact.lastName}
											</span>
											{#if contact.email}
												<p class="mt-0.5 truncate text-sm text-theme-secondary">{contact.email}</p>
											{/if}
											{#if contact.phone}
												<p class="mt-1 text-sm text-theme-muted">{contact.phone}</p>
											{/if}
										</div>
										{#if contact.notes || contact.isPrimary}
											<div class="flex flex-wrap items-center gap-2">
												{#if contact.isPrimary}
													<span class="badge-primary">Primary</span>
												{/if}
												{#if contact.notes}
													<span class="text-xs text-theme-muted italic">{contact.notes}</span>
												{/if}
											</div>
										{/if}
									</div>
								{/each}
							</div>
						{:else}
							<p class="py-6 text-center text-theme-muted">No contacts added yet.</p>
						{/if}
					</div>
				</section>

				<!-- Address History (only shown if there are previous addresses) -->
				{#if inactiveAddresses.length > 0}
					<section
						class="overflow-hidden rounded-xl border border-theme bg-theme-card shadow-theme-md"
					>
						<div class="bg-theme-secondary/50 border-b border-theme px-5 py-3">
							<SectionHeader title="Address History" />
						</div>
						<div class="px-5 py-5">
							<div class="space-y-3">
								{#each inactiveAddresses as address (address.id)}
									<div class="bg-theme-secondary/30 rounded-lg border border-theme p-4 opacity-75">
										<div class="flex items-start justify-between">
											<div>
												<div class="flex items-center gap-2">
													<span class="font-medium text-theme-secondary"
														>{address.name || 'Previous Address'}</span
													>
													<span class="badge-neutral">Inactive</span>
												</div>
												<p class="mt-2 text-sm text-theme-muted">{address.streetAddress}</p>
												<p class="text-sm text-theme-muted">
													{address.city}, {address.state}
													{address.zipCode}
												</p>
											</div>
										</div>
									</div>
								{/each}
							</div>
						</div>
					</section>
				{/if}

				<!-- Linked Accounts -->
				<details
					class="group overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
				>
					<summary
						class="flex cursor-pointer items-center justify-between bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3 select-none"
					>
						<span class="flex items-center gap-3">
							<span class="text-lg font-semibold text-theme">Accounts</span>
							<span class="text-sm text-theme-muted">({accounts.length})</span>
						</span>
						<span class="flex items-center gap-2">
							<button
								type="button"
								onclick={(e) => {
									e.preventDefault();
									handleAddAccount();
								}}
								class="hidden items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium text-primary-500 transition-colors group-open:inline-flex hover:bg-primary-500/10"
							>
								<IconPlus />
								<span>Add</span>
							</button>
							<svg
								class="h-5 w-5 text-theme-muted transition-transform group-open:rotate-180"
								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>
						</span>
					</summary>
					<div class="border-t border-primary-500/20 px-5 py-5">
						{#if accounts.length > 0}
							<div class="space-y-2">
								{#each accounts as account (account.id)}
									<a
										href="/admin/accounts/{account.id}"
										class="bg-theme-secondary/50 flex items-center justify-between rounded-lg border border-theme p-4 transition-all hover:border-primary-500/30 hover:bg-theme-secondary hover:shadow-sm"
									>
										<div class="flex flex-wrap items-center gap-x-3 gap-y-1">
											<span class="font-medium text-primary-600 dark:text-primary-400">
												{account.name}
											</span>
											<span class={getStatusBadgeClass(account.status)}>{account.status}</span>
										</div>
										<IconChevronRight class="h-5 w-5 shrink-0 text-theme-muted" />
									</a>
								{/each}
							</div>
						{:else}
							<p class="py-6 text-center text-theme-muted">No accounts linked to this customer.</p>
						{/if}
					</div>
				</details>

				<!-- Danger Zone -->
				<details
					class="group overflow-hidden rounded-xl border border-error-500/30 bg-error-50/50 shadow-theme dark:bg-error-950/20"
				>
					<summary
						class="flex cursor-pointer items-center justify-between bg-linear-to-r from-error-500/10 to-transparent px-5 py-3 select-none"
					>
						<span class="text-lg font-semibold text-error-700 dark:text-error-400">Danger Zone</span
						>
						<svg
							class="h-5 w-5 text-error-500 transition-transform group-open:rotate-180"
							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>
					</summary>
					<div class="space-y-4 border-t border-error-500/20 px-5 py-5">
						<p class="text-sm text-error-600 dark:text-error-300">
							Deleting this customer will remove all associated contacts, addresses, and unlink all
							accounts. This action cannot be undone.
						</p>
						<button type="button" class="btn-danger" onclick={handleDeleteCustomer}
							>Delete Customer</button
						>
					</div>
				</details>
			</div>

			<!-- Form Drawer -->
			<FormDrawer open={drawerOpen} title={drawerTitle()} onClose={closeDrawer}>
				{#if drawerMode?.type === 'customer' && customer}
					<CustomerForm {customer} {waveCustomers} onSuccess={handleFormSuccess} onCancel={closeDrawer} />
				{:else if drawerMode?.type === 'contact' && drawerMode.mode === 'add' && customer}
					<ContactForm
						customerId={customer.id}
						onSuccess={handleFormSuccess}
						onCancel={closeDrawer}
					/>
				{:else if drawerMode?.type === 'contact' && drawerMode.mode === 'edit' && customer}
					<ContactForm
						contact={drawerMode.data}
						customerId={customer.id}
						onSuccess={handleFormSuccess}
						onCancel={closeDrawer}
					/>
				{/if}
			</FormDrawer>

			<!-- Delete Modal -->
			<DeleteModal
				open={deleteModalOpen}
				title={deleteTarget
					? `Delete ${deleteTarget.type.charAt(0).toUpperCase() + deleteTarget.type.slice(1)}`
					: ''}
				message={deleteTarget
					? `Are you sure you want to delete "${deleteTarget.name}"? This action cannot be undone.`
					: ''}
				requireConfirmation={deleteTarget?.type === 'customer'}
				loading={deleteLoading}
				onConfirm={confirmDelete}
				onCancel={closeDeleteModal}
			/>
		{:else}
			<div class="empty-state">
				<svg class="empty-state-icon" 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>
