<script lang="ts">
	import SectionHeader from '$lib/components/admin/SectionHeader.svelte';
	import ItemActions from '$lib/components/admin/ItemActions.svelte';
	import { IconEdit, IconTrash } from '$lib/components/icons';
	import { formatDate } from '$lib/utils/date';
	import { fromGlobalId } from '$lib/utils/relay';

	interface Revenue {
		id: string;
		amount: number | null;
		startDate: string | null;
		endDate: string | null;
		waveServiceId: string | null;
	}

	interface WaveProduct {
		id: string;
		name: string;
		description: string | null;
		unitPrice: number;
		isArchived: boolean;
	}

	interface Props {
		revenues: Revenue[];
		waveProducts?: WaveProduct[];
		onAdd: () => void;
		onEdit: (revenue: Revenue) => void;
		onDelete: (revenueId: string) => void;
	}

	let { revenues, waveProducts = [], onAdd, onEdit, onDelete }: Props = $props();

	let currentRevenue = $derived(revenues.find((r) => !r.endDate));
	let historicalRevenues = $derived(revenues.filter((r) => r.endDate));
	let showHistoricalRevenues = $state(false);

	function formatCurrency(amount: number | null | undefined): string {
		if (amount === null || amount === undefined) return '$0.00';
		return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
	}

	function getLinkedProduct(waveServiceId: string | null | undefined): WaveProduct | null {
		if (!waveServiceId) return null;
		return waveProducts.find((p) => fromGlobalId(p.id) === waveServiceId) ?? null;
	}
</script>

<div class="card-padded">
	<SectionHeader title="Revenue" buttonText="Add" onButtonClick={onAdd} />

	{#if currentRevenue}
		{@const linkedProduct = getLinkedProduct(currentRevenue.waveServiceId)}
		<!-- Current revenue shown prominently -->
		<div
			class="mb-4 rounded-lg border-2 border-green-200 bg-green-50 p-4 dark:border-green-800 dark:bg-green-900/20"
		>
			<div class="flex items-start justify-between">
				<div>
					<div class="flex items-center gap-2">
						<span class="text-2xl font-bold text-green-700 dark:text-green-400">
							{formatCurrency(currentRevenue.amount)}
						</span>
						<span class="badge-success">Current</span>
						{#if currentRevenue.waveServiceId}
							<span class="badge-primary">Linked</span>
						{/if}
					</div>
					<p class="mt-1 text-sm text-green-600 dark:text-green-500">
						As of {formatDate(currentRevenue.startDate) || '—'}
					</p>
					{#if linkedProduct}
						<p class="mt-1 text-sm text-green-600 dark:text-green-500">
							Wave: {linkedProduct.name}
						</p>
						<p class="mt-1 font-mono text-xs text-green-500 dark:text-green-600">
							{currentRevenue.waveServiceId}
						</p>
					{:else if currentRevenue.waveServiceId}
						<p class="mt-1 font-mono text-xs text-green-500 dark:text-green-600">
							{currentRevenue.waveServiceId}
						</p>
					{/if}
				</div>
				<div class="flex items-center gap-1">
					<button
						type="button"
						onclick={() => onEdit(currentRevenue)}
						class="rounded p-1.5 text-green-600 hover:bg-green-100 dark:text-green-400 dark:hover:bg-green-900/40"
						aria-label="Edit revenue"
					>
						<IconEdit />
					</button>
					<button
						type="button"
						onclick={() => onDelete(currentRevenue.id)}
						class="rounded p-1.5 text-green-600 hover:bg-red-50 hover:text-red-500 dark:text-green-400 dark:hover:bg-red-900/20"
						aria-label="Delete revenue"
					>
						<IconTrash />
					</button>
				</div>
			</div>
		</div>
	{:else}
		<p class="mb-4 text-center text-theme-muted">No current revenue rate set.</p>
	{/if}

	<!-- Historical revenues (collapsed by default) -->
	{#if historicalRevenues.length > 0}
		<div class="border-t border-theme pt-4">
			<button
				type="button"
				onclick={() => (showHistoricalRevenues = !showHistoricalRevenues)}
				class="flex w-full items-center justify-between text-sm font-medium text-theme-secondary hover:text-theme"
			>
				<span>Historical Revenue ({historicalRevenues.length})</span>
				<svg
					class="h-4 w-4 transition-transform {showHistoricalRevenues ? '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 showHistoricalRevenues}
				<div class="mt-3 space-y-2">
					{#each historicalRevenues as revenue (revenue.id)}
						{@const linkedProduct = getLinkedProduct(revenue.waveServiceId)}
						<div
							class="flex items-center justify-between rounded-lg border border-theme bg-theme p-3"
						>
							<div>
								<div class="flex items-center gap-2">
									<span class="font-medium text-theme">{formatCurrency(revenue.amount)}</span>
									{#if revenue.waveServiceId}
										<span class="badge-primary text-xs">Linked</span>
									{/if}
								</div>
								<p class="text-xs text-theme-muted">
									{formatDate(revenue.startDate) || '—'} - {formatDate(revenue.endDate) ||
										'Present'}
								</p>
								{#if linkedProduct}
									<p class="text-xs text-theme-muted">Wave: {linkedProduct.name}</p>
									<p class="font-mono text-xs text-theme-muted">{revenue.waveServiceId}</p>
								{:else if revenue.waveServiceId}
									<p class="font-mono text-xs text-theme-muted">{revenue.waveServiceId}</p>
								{/if}
							</div>
							<ItemActions
								editLabel="Edit revenue"
								deleteLabel="Delete revenue"
								onEdit={() => onEdit(revenue)}
								onDelete={() => onDelete(revenue.id)}
							/>
						</div>
					{/each}
				</div>
			{/if}
		</div>
	{/if}
</div>
