<script lang="ts">
	import type { NexusRevenue, NexusProject, WaveProduct } from './types';
	import { fromGlobalId } from '$lib/utils/relay';

	interface CustomerInfo {
		customerName: string;
		waveCustomerId: string | null;
	}

	interface Account {
		id: string;
		name: string;
	}

	interface Props {
		customer: CustomerInfo;
		revenues: NexusRevenue[];
		projects: NexusProject[];
		waveProducts: WaveProduct[];
		accounts: Account[];
		onLinkCustomer: () => void;
		onLinkRevenue: (revenueId: string, accountName: string) => void;
		onLinkProject: (projectId: string, projectName: string) => void;
		onCreateInvoice: () => void;
	}

	let {
		customer,
		revenues,
		projects,
		waveProducts,
		accounts,
		onLinkCustomer,
		onLinkRevenue,
		onLinkProject,
		onCreateInvoice
	}: Props = $props();

	// Validation checks
	let customerLinked = $derived(!!customer.waveCustomerId);
	let unlinkedRevenues = $derived(revenues.filter((r) => !r.waveServiceId));
	let unlinkedProjects = $derived(projects.filter((p) => !p.waveServiceId));
	let linkedRevenues = $derived(revenues.filter((r) => r.waveServiceId));
	let linkedProjects = $derived(projects.filter((p) => p.waveServiceId));
	let hasLinkedItems = $derived(linkedRevenues.length > 0 || linkedProjects.length > 0);
	let totalErrors = $derived(
		(customerLinked ? 0 : 1) + unlinkedRevenues.length + unlinkedProjects.length
	);
	let isValid = $derived(totalErrors === 0 && hasLinkedItems);

	// Get product name for a linked item (waveServiceId is stored as decoded UUID)
	function getProductName(waveServiceId: string | null): string {
		if (!waveServiceId) return 'Not linked';
		const product = waveProducts.find((p) => fromGlobalId(p.id) === waveServiceId);
		return product?.name ?? 'Unknown product';
	}

	// Get account name for revenue (accountId is UUID, account.id is GlobalID)
	function getAccountName(accountId: string): string {
		const account = accounts.find((a) => fromGlobalId(a.id) === accountId);
		return account?.name ?? 'Unknown Account';
	}

	// Format date
	function formatShortDate(dateStr: string | null): string {
		if (!dateStr) return '';
		return new Date(dateStr + 'T00:00:00').toLocaleDateString('en-US', {
			month: 'short',
			day: 'numeric',
			year: 'numeric'
		});
	}

	// Format currency
	function formatCurrency(value: string | number): string {
		const num = typeof value === 'string' ? parseFloat(value.replace(/,/g, '')) : value;
		return new Intl.NumberFormat('en-US', {
			style: 'currency',
			currency: 'USD'
		}).format(num);
	}
</script>

<div class="space-y-6">
	<!-- Status Summary -->
	<div class="card-padded">
		{#if isValid}
			<div class="flex items-center gap-3">
				<div class="flex h-10 w-10 items-center justify-center rounded-full bg-success-500/20">
					<svg
						class="h-5 w-5 text-success-600 dark:text-success-400"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M5 13l4 4L19 7"
						/>
					</svg>
				</div>
				<div>
					<h3 class="font-medium text-theme">Ready to create Wave invoice</h3>
					<p class="text-sm text-theme-muted">
						All items are linked to Wave. Click below to create the invoice.
					</p>
				</div>
			</div>
			<button
				type="button"
				onclick={onCreateInvoice}
				class="mt-4 w-full rounded-lg bg-accent6-500 px-4 py-2.5 font-medium text-white transition-colors hover:bg-accent6-600"
			>
				Create Wave Invoice
			</button>
		{:else if !hasLinkedItems && customerLinked && totalErrors === 0}
			<div class="flex items-center gap-3">
				<div class="flex h-10 w-10 items-center justify-center rounded-full bg-warning-500/20">
					<svg
						class="h-5 w-5 text-warning-600 dark:text-warning-400"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
						/>
					</svg>
				</div>
				<div>
					<h3 class="font-medium text-theme">No line items</h3>
					<p class="text-sm text-theme-muted">
						Add at least one linked revenue or project to create the invoice.
					</p>
				</div>
			</div>
		{:else}
			<div class="flex items-center gap-3">
				<div class="flex h-10 w-10 items-center justify-center rounded-full bg-warning-500/20">
					<svg
						class="h-5 w-5 text-warning-600 dark:text-warning-400"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
						/>
					</svg>
				</div>
				<div>
					<h3 class="font-medium text-theme">
						{totalErrors} item{totalErrors !== 1 ? 's' : ''} need{totalErrors === 1 ? 's' : ''} linking
					</h3>
					<p class="text-sm text-theme-muted">
						Link all items to Wave products before creating the invoice.
					</p>
				</div>
			</div>
		{/if}
	</div>

	<!-- Customer Section -->
	<div class="card-padded">
		<h3 class="mb-4 text-sm font-medium text-theme-muted">Customer</h3>

		<div
			class="rounded-lg border p-4 {customerLinked
				? 'border-success-200 bg-success-50 dark:border-success-800 dark:bg-success-900/20'
				: 'border-warning-200 bg-warning-50 dark:border-warning-800 dark:bg-warning-900/20'}"
		>
			<div class="flex items-center justify-between gap-4">
				<div class="min-w-0 flex-1">
					<div class="flex items-center gap-2">
						<span class="font-medium text-theme">{customer.customerName}</span>
						{#if customerLinked}
							<span class="badge-success">Linked</span>
						{:else}
							<span class="badge-warning">Not Linked</span>
						{/if}
					</div>
					{#if customerLinked}
						<p class="mt-1 truncate text-sm text-theme-muted">
							Wave Customer ID: {customer.waveCustomerId}
						</p>
					{:else}
						<p class="mt-1 text-sm text-warning-600 dark:text-warning-400">
							Link this customer to a Wave customer to continue.
						</p>
					{/if}
				</div>
				<button
					type="button"
					onclick={onLinkCustomer}
					class="shrink-0 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors {customerLinked
						? 'bg-theme text-theme-secondary hover:bg-black/5 dark:hover:bg-white/10'
						: 'bg-warning-500 text-white hover:bg-warning-600'}"
				>
					{customerLinked ? 'Change' : 'Link'}
				</button>
			</div>
		</div>
	</div>

	<!-- Revenues Section -->
	<div class="card-padded">
		<div class="mb-4 flex items-center justify-between">
			<h3 class="text-sm font-medium text-theme-muted">Revenues</h3>
			{#if unlinkedRevenues.length > 0}
				<span
					class="rounded-full bg-warning-500/20 px-2 py-0.5 text-xs font-medium text-warning-600 dark:text-warning-400"
				>
					{unlinkedRevenues.length} unlinked
				</span>
			{:else if revenues.length > 0}
				<span
					class="rounded-full bg-success-500/20 px-2 py-0.5 text-xs font-medium text-success-600 dark:text-success-400"
				>
					All linked
				</span>
			{/if}
		</div>

		{#if revenues.length === 0}
			<p class="text-sm text-theme-muted italic">No revenues on this invoice.</p>
		{:else}
			<div class="space-y-2">
				{#each revenues as revenue (revenue.id)}
					{@const accountName = getAccountName(revenue.accountId)}
					{@const isLinked = !!revenue.waveServiceId}
					<div
						class="rounded-lg border p-3 {isLinked
							? 'border-theme bg-theme-secondary'
							: 'border-warning-200 bg-warning-50 dark:border-warning-800 dark:bg-warning-900/20'}"
					>
						<div class="flex items-start justify-between gap-3">
							<div class="min-w-0 flex-1">
								<div class="flex items-center gap-2">
									<span class="text-sm font-medium text-theme">{accountName}</span>
									{#if isLinked}
										<span class="badge-success">Linked</span>
									{:else}
										<span class="badge-warning">Not Linked</span>
									{/if}
								</div>
								<p class="text-xs text-theme-muted">
									{formatShortDate(revenue.startDate)}
									{#if revenue.endDate}
										- {formatShortDate(revenue.endDate)}
									{:else}
										- Ongoing
									{/if}
								</p>
								{#if isLinked}
									<p class="mt-1 text-xs text-theme-muted">
										Product: {getProductName(revenue.waveServiceId)}
									</p>
								{/if}
							</div>
							<div class="flex items-center gap-2">
								<span class="text-sm font-semibold text-secondary-600 dark:text-secondary-400">
									{formatCurrency(revenue.amount)}
								</span>
								<button
									type="button"
									onclick={() => onLinkRevenue(revenue.id, accountName)}
									class="rounded px-2 py-1 text-xs font-medium transition-colors {isLinked
										? 'text-theme-muted hover:bg-black/5 dark:hover:bg-white/10'
										: 'bg-warning-500 text-white hover:bg-warning-600'}"
								>
									{isLinked ? 'Change' : 'Link'}
								</button>
							</div>
						</div>
					</div>
				{/each}
			</div>
		{/if}
	</div>

	<!-- Projects Section -->
	<div class="card-padded">
		<div class="mb-4 flex items-center justify-between">
			<h3 class="text-sm font-medium text-theme-muted">Projects</h3>
			{#if unlinkedProjects.length > 0}
				<span
					class="rounded-full bg-warning-500/20 px-2 py-0.5 text-xs font-medium text-warning-600 dark:text-warning-400"
				>
					{unlinkedProjects.length} unlinked
				</span>
			{:else if projects.length > 0}
				<span
					class="rounded-full bg-success-500/20 px-2 py-0.5 text-xs font-medium text-success-600 dark:text-success-400"
				>
					All linked
				</span>
			{/if}
		</div>

		{#if projects.length === 0}
			<p class="text-sm text-theme-muted italic">No projects on this invoice.</p>
		{:else}
			<div class="space-y-2">
				{#each projects as project (project.id)}
					{@const isLinked = !!project.waveServiceId}
					<div
						class="rounded-lg border p-3 {isLinked
							? 'border-theme bg-theme-secondary'
							: 'border-warning-200 bg-warning-50 dark:border-warning-800 dark:bg-warning-900/20'}"
					>
						<div class="flex items-start justify-between gap-3">
							<div class="min-w-0 flex-1">
								<div class="flex items-center gap-2">
									<span class="text-sm font-medium text-theme">{project.name}</span>
									{#if isLinked}
										<span class="badge-success">Linked</span>
									{:else}
										<span class="badge-warning">Not Linked</span>
									{/if}
								</div>
								<p class="text-xs text-theme-muted">{formatShortDate(project.date)}</p>
								{#if isLinked}
									<p class="mt-1 text-xs text-theme-muted">
										Product: {getProductName(project.waveServiceId)}
									</p>
								{/if}
							</div>
							<div class="flex items-center gap-2">
								<span class="text-sm font-semibold text-accent-600 dark:text-accent-400">
									{formatCurrency(project.amount)}
								</span>
								<button
									type="button"
									onclick={() => onLinkProject(project.id, project.name)}
									class="rounded px-2 py-1 text-xs font-medium transition-colors {isLinked
										? 'text-theme-muted hover:bg-black/5 dark:hover:bg-white/10'
										: 'bg-warning-500 text-white hover:bg-warning-600'}"
								>
									{isLinked ? 'Change' : 'Link'}
								</button>
							</div>
						</div>
					</div>
				{/each}
			</div>
		{/if}
	</div>
</div>
