<script lang="ts">
	import type { PageData } from './$types';
	import { goto, invalidateAll } from '$app/navigation';
	import { client } from '$lib/graphql/client';
	import { ContentContainer } from '$lib/components/layout';
	import { PageHeader, SectionHeader } from '$lib/components/admin';
	import { IconEdit, IconTrash, IconChevronRight } from '$lib/components/icons';
	import { formatDate } from '$lib/utils/date';
	import { DeleteModal } from '$lib/components/modals';
	import { FormDrawer } from '$lib/components/drawers';
	import { AccountForm, AccountContactForm, AccountAddressForm } from '$lib/components/forms';
	import {
		DELETE_ACCOUNT,
		DELETE_ACCOUNT_CONTACT,
		DELETE_ACCOUNT_ADDRESS
	} from '$lib/graphql/mutations/account';
	import type { AccountContact, AccountAddress } from '$lib/graphql/queries/account';

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

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

	// Split revenues into active (current) and historical
	let activeRevenue = $derived(revenues.find((r) => r.isActive) ?? null);
	let historicalRevenues = $derived(revenues.filter((r) => !r.isActive));

	function formatCurrency(amount: string): string {
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD'
		}).format(parseFloat(amount));
	}

	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 state
	let drawerOpen = $state(false);
	type DrawerMode =
		| { type: 'account'; mode: 'edit' }
		| { type: 'contact'; mode: 'add' }
		| { type: 'contact'; mode: 'edit'; data: AccountContact }
		| { type: 'address'; mode: 'add' }
		| { type: 'address'; mode: 'edit'; data: AccountAddress };
	let drawerMode = $state<DrawerMode | null>(null);

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

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

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

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

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

	function handleEditAddress(address: AccountAddress) {
		drawerMode = { type: 'address', mode: 'edit', data: address };
		drawerOpen = true;
	}

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

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

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

	function handleDeleteAddress(address: AccountAddress) {
		deleteTarget = {
			type: 'address',
			id: address.id,
			name: address.name || address.streetAddress
		};
		deleteModalOpen = true;
	}

	function handleDeleteAccount() {
		if (!account) return;
		deleteTarget = {
			type: 'account',
			id: account.id,
			name: account.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_ACCOUNT_CONTACT,
					variables: { id: deleteTarget.id }
				});
			} else if (deleteTarget.type === 'address') {
				await client.mutate({
					mutation: DELETE_ACCOUNT_ADDRESS,
					variables: { id: deleteTarget.id }
				});
			} else if (deleteTarget.type === 'account') {
				await client.mutate({
					mutation: DELETE_ACCOUNT,
					variables: { id: deleteTarget.id }
				});
				closeDeleteModal();
				await goto('/admin/accounts');
				return;
			}

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

	// 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>{account?.name ?? 'Account'} - Admin - Nexus</title>
</svelte:head>

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

			<div class="space-y-6">
				<!-- Account Information -->
				<section
					class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
				>
					<div
						class="border-b border-primary-500/20 bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3"
					>
						<SectionHeader
							title="Account Information"
							buttonText="Edit"
							buttonIcon="edit"
							onButtonClick={handleEditAccount}
						/>
					</div>
					<div class="grid grid-cols-1 gap-6 px-5 py-5 sm:grid-cols-2">
						<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>
						{#if account.customer}
							<div>
								<p class="detail-label">Parent Customer</p>
								<a
									href="/admin/customers/{account.customer.id}"
									class="text-primary-500 hover:text-primary-600"
								>
									{account.customer.name} →
								</a>
							</div>
						{/if}
						<div>
							<p class="detail-label">Monthly Revenue</p>
							{#if activeRevenue}
								<p class="text-theme">{formatCurrency(activeRevenue.amount)}</p>
								<p class="text-sm text-theme-secondary">
									Since {formatDate(activeRevenue.startDate)}
									{#if activeRevenue.waveServiceId}
										<span class="ml-1 badge-primary">Wave</span>
										{#if activeRevenue.waveProductName}
											<span class="ml-1 text-theme-muted">({activeRevenue.waveProductName})</span>
										{/if}
									{/if}
								</p>
							{:else}
								<p class="text-theme-muted">Not set</p>
							{/if}
						</div>
					</div>
				</section>

				<!-- Contacts -->
				<section
					class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
				>
					<div
						class="border-b border-primary-500/20 bg-linear-to-r from-primary-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>

				<!-- Revenue History (only shown if there are previous rates) -->
				{#if historicalRevenues.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="Revenue History" />
						</div>
						<div class="px-5 py-5">
							<div class="space-y-3">
								{#each historicalRevenues as revenue (revenue.id)}
									<div class="bg-theme-secondary/30 rounded-lg border border-theme p-3 opacity-75">
										<div class="flex items-center justify-between">
											<div class="flex items-center gap-2">
												<span class="font-medium text-theme-secondary">
													{formatCurrency(revenue.amount)}
												</span>
												{#if revenue.waveServiceId}
													<span class="text-xs text-primary-500">Wave</span>
													{#if revenue.waveProductName}
														<span class="text-xs text-theme-muted">({revenue.waveProductName})</span
														>
													{/if}
												{/if}
												<span class="badge-neutral">Inactive</span>
											</div>
											<p class="text-sm text-theme-muted">
												{formatDate(revenue.startDate)} – {formatDate(revenue.endDate)}
											</p>
										</div>
									</div>
								{/each}
							</div>
						</div>
					</section>
				{/if}

				<!-- Service Locations (Addresses) -->
				<section
					class="overflow-hidden rounded-xl border border-primary-500/20 bg-theme-card shadow-theme-md"
				>
					<div
						class="border-b border-primary-500/20 bg-linear-to-r from-primary-500/10 to-transparent px-5 py-3"
					>
						<SectionHeader
							title="Service Locations"
							buttonText="Add"
							onButtonClick={handleAddAddress}
						/>
					</div>
					<div class="px-5 py-5">
						{#if addresses.length > 0}
							<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
								{#each addresses as address (address.id)}
									<a
										href="/admin/accounts/{account.id}/locations/{address.id}"
										class="group/card bg-theme-secondary/50 relative flex items-center justify-between rounded-lg border border-theme p-3 transition-colors hover:bg-theme-secondary"
									>
										<div>
											<span class="font-medium text-theme">
												{address.name ||
													(addresses.length === 1 ? 'Primary Service Address' : 'Service Location')}
											</span>
											<p class="mt-0.5 text-sm text-theme-secondary">{address.streetAddress}</p>
											<p class="text-sm text-theme-muted">
												{address.city}, {address.state}
												{address.zipCode}
											</p>
											{#if address.isPrimary || address.notes}
												<div class="mt-1 flex flex-wrap items-center gap-2">
													{#if address.isPrimary}
														<span class="badge-primary">Primary</span>
													{/if}
													{#if address.notes}
														<span class="text-xs text-theme-muted italic">{address.notes}</span>
													{/if}
												</div>
											{/if}
										</div>
										<IconChevronRight
											class="h-5 w-5 text-theme-muted group-hover/card:text-theme"
										/>
									</a>
								{/each}
							</div>
						{:else}
							<p class="py-6 text-center text-theme-muted">No service locations added yet.</p>
						{/if}
					</div>
				</section>

				<!-- 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 account will remove all associated contacts and service locations. This
							action cannot be undone.
						</p>
						<button type="button" class="btn-danger" onclick={handleDeleteAccount}
							>Delete Account</button
						>
					</div>
				</details>
			</div>

			<!-- Form Drawer -->
			<FormDrawer open={drawerOpen} title={drawerTitle()} onClose={closeDrawer}>
				{#if drawerMode?.type === 'account'}
					<AccountForm
						{account}
						{activeRevenue}
						waveProducts={data.waveProducts ?? []}
						onSuccess={handleFormSuccess}
						onCancel={closeDrawer}
					/>
				{:else if drawerMode?.type === 'contact'}
					<AccountContactForm
						contact={drawerMode.mode === 'edit' ? drawerMode.data : undefined}
						accountId={account.id}
						onSuccess={handleFormSuccess}
						onCancel={closeDrawer}
					/>
				{:else if drawerMode?.type === 'address'}
					<AccountAddressForm
						address={drawerMode.mode === 'edit' ? drawerMode.data : undefined}
						accountId={account.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 === 'account'}
				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">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>
