<script lang="ts">
	import {
		ArrowLeft,
		Download,
		TrendingUp,
		TrendingDown,
		DollarSign,
		Users,
		Clock,
		AlertCircle,
		CheckCircle2,
		XCircle,
		BarChart3,
		PieChart,
		FileSpreadsheet,
		Mail
	} from 'lucide-svelte';
	import { enhance } from '$app/forms';

	let { data, form } = $props();
	const { analytics, effectiveness } = data;

	let isExporting = $state<string | null>(null);

	// Format currency
	function formatCurrency(amount: number): string {
		return new Intl.NumberFormat('en-EU', {
			style: 'currency',
			currency: 'EUR'
		}).format(amount);
	}

	// Download CSV from form result
	function downloadCSV(csv: string, filename: string) {
		const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
		const url = URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		link.download = filename;
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
		URL.revokeObjectURL(url);
	}

	// Handle CSV download after form submission
	$effect(() => {
		if (form?.csv && form?.filename) {
			downloadCSV(form.csv, form.filename);
		}
	});

	// Calculate chart bar heights
	function getBarHeight(amount: number, max: number): number {
		if (max === 0) return 0;
		return Math.max(4, (amount / max) * 100);
	}

	const maxMonthlyAmount = analytics?.paymentsByMonth
		? Math.max(...analytics.paymentsByMonth.map((m: any) => m.amount), 1)
		: 1;
</script>

<svelte:head>
	<title>Dues Reports | Monaco USA</title>
</svelte:head>

<div class="space-y-6">
	<!-- Header -->
	<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
		<div class="flex items-center gap-4">
			<a
				href="/board/dues"
				class="flex items-center justify-center rounded-lg border border-slate-200 p-2 hover:bg-slate-50"
			>
				<ArrowLeft class="h-5 w-5 text-slate-600" />
			</a>
			<div>
				<h1 class="text-2xl font-bold text-slate-900">Dues Reports</h1>
				<p class="text-slate-500">Analytics and financial reporting</p>
			</div>
		</div>
	</div>

	<!-- Summary Cards -->
	<div class="grid grid-cols-2 gap-4 lg:grid-cols-4">
		<div class="glass-card p-5">
			<div class="flex items-center justify-between">
				<div>
					<p class="text-sm text-slate-500">Collected This Month</p>
					<p class="mt-1 text-2xl font-bold text-slate-900">
						{formatCurrency(analytics?.totalCollectedThisMonth || 0)}
					</p>
				</div>
				<div class="rounded-lg bg-green-100 p-3">
					<DollarSign class="h-6 w-6 text-green-600" />
				</div>
			</div>
		</div>

		<div class="glass-card p-5">
			<div class="flex items-center justify-between">
				<div>
					<p class="text-sm text-slate-500">Collected This Year</p>
					<p class="mt-1 text-2xl font-bold text-slate-900">
						{formatCurrency(analytics?.totalCollectedThisYear || 0)}
					</p>
				</div>
				<div class="rounded-lg bg-blue-100 p-3">
					<TrendingUp class="h-6 w-6 text-blue-600" />
				</div>
			</div>
		</div>

		<div class="glass-card p-5">
			<div class="flex items-center justify-between">
				<div>
					<p class="text-sm text-slate-500">Outstanding</p>
					<p class="mt-1 text-2xl font-bold text-red-600">
						{formatCurrency(analytics?.totalOutstanding || 0)}
					</p>
				</div>
				<div class="rounded-lg bg-red-100 p-3">
					<AlertCircle class="h-6 w-6 text-red-600" />
				</div>
			</div>
		</div>

		<div class="glass-card p-5">
			<div class="flex items-center justify-between">
				<div>
					<p class="text-sm text-slate-500">Reminders Sent</p>
					<p class="mt-1 text-2xl font-bold text-slate-900">
						{analytics?.remindersSentThisMonth || 0}
					</p>
					<p class="text-xs text-slate-400">This month</p>
				</div>
				<div class="rounded-lg bg-purple-100 p-3">
					<Mail class="h-6 w-6 text-purple-600" />
				</div>
			</div>
		</div>
	</div>

	<div class="grid gap-6 lg:grid-cols-2">
		<!-- Collection Trend Chart -->
		<div class="glass-card p-6">
			<div class="mb-4 flex items-center justify-between">
				<h2 class="flex items-center gap-2 font-semibold text-slate-900">
					<BarChart3 class="h-5 w-5 text-monaco-600" />
					Collection Trend (12 Months)
				</h2>
			</div>

			<div class="h-64">
				{#if analytics?.paymentsByMonth && analytics.paymentsByMonth.length > 0}
					<div class="flex h-full items-end gap-2">
						{#each analytics.paymentsByMonth as month, i}
							<div class="flex flex-1 flex-col items-center">
								<div
									class="w-full rounded-t bg-monaco-500 transition-all hover:bg-monaco-600"
									style="height: {getBarHeight(month.amount, maxMonthlyAmount)}%"
									title="{month.month}: {formatCurrency(month.amount)} ({month.count} payments)"
								></div>
								<p class="mt-2 text-[10px] text-slate-500 sm:text-xs">
									{month.month.split(' ')[0].slice(0, 3)}
								</p>
							</div>
						{/each}
					</div>
				{:else}
					<div class="flex h-full items-center justify-center">
						<p class="text-slate-400">No payment data available</p>
					</div>
				{/if}
			</div>
		</div>

		<!-- Status Breakdown -->
		<div class="glass-card p-6">
			<div class="mb-4 flex items-center justify-between">
				<h2 class="flex items-center gap-2 font-semibold text-slate-900">
					<PieChart class="h-5 w-5 text-monaco-600" />
					Member Status Breakdown
				</h2>
			</div>

			<div class="space-y-4">
				{#if analytics?.statusBreakdown}
					{@const statusConfig = {
						current: { icon: CheckCircle2, color: 'bg-green-500', textColor: 'text-green-600', label: 'Current' },
						due_soon: { icon: Clock, color: 'bg-yellow-500', textColor: 'text-yellow-600', label: 'Due Soon' },
						overdue: { icon: AlertCircle, color: 'bg-red-500', textColor: 'text-red-600', label: 'Overdue' },
						never_paid: { icon: XCircle, color: 'bg-slate-400', textColor: 'text-slate-500', label: 'Never Paid' }
					}}
					{#each analytics.statusBreakdown as status}
						{@const config = statusConfig[status.status as keyof typeof statusConfig]}
						<div class="flex items-center gap-3">
							<svelte:component this={config.icon} class="h-5 w-5 {config.textColor}" />
							<div class="flex-1">
								<div class="flex items-center justify-between">
									<span class="text-sm font-medium text-slate-700">{config.label}</span>
									<span class="text-sm text-slate-500">
										{status.count} ({status.percentage.toFixed(1)}%)
									</span>
								</div>
								<div class="mt-1 h-2 overflow-hidden rounded-full bg-slate-100">
									<div
										class="h-full {config.color} transition-all"
										style="width: {status.percentage}%"
									></div>
								</div>
							</div>
						</div>
					{/each}
				{/if}
			</div>

			<div class="mt-6 border-t border-slate-200 pt-4">
				<div class="flex items-center justify-between text-sm">
					<span class="text-slate-500">Total Members</span>
					<span class="font-semibold text-slate-900">{analytics?.totalMembers || 0}</span>
				</div>
			</div>
		</div>
	</div>

	<!-- Reminder Effectiveness -->
	<div class="glass-card p-6">
		<div class="mb-4 flex items-center justify-between">
			<h2 class="flex items-center gap-2 font-semibold text-slate-900">
				<Mail class="h-5 w-5 text-monaco-600" />
				Reminder Effectiveness
			</h2>
		</div>

		<div class="grid gap-4 sm:grid-cols-4">
			<div class="rounded-lg bg-slate-50 p-4">
				<p class="text-sm text-slate-500">Total Reminders Sent</p>
				<p class="mt-1 text-2xl font-bold text-slate-900">{effectiveness?.totalRemindersSent || 0}</p>
			</div>
			<div class="rounded-lg bg-green-50 p-4">
				<p class="text-sm text-slate-500">Paid Within 7 Days</p>
				<p class="mt-1 text-2xl font-bold text-green-600">{effectiveness?.paidWithin7Days || 0}</p>
			</div>
			<div class="rounded-lg bg-blue-50 p-4">
				<p class="text-sm text-slate-500">Paid Within 30 Days</p>
				<p class="mt-1 text-2xl font-bold text-blue-600">{effectiveness?.paidWithin30Days || 0}</p>
			</div>
			<div class="rounded-lg bg-purple-50 p-4">
				<p class="text-sm text-slate-500">Effectiveness Rate</p>
				<p class="mt-1 text-2xl font-bold text-purple-600">
					{(effectiveness?.effectivenessRate || 0).toFixed(1)}%
				</p>
			</div>
		</div>
	</div>

	<!-- Export Section -->
	<div class="glass-card p-6">
		<div class="mb-4">
			<h2 class="flex items-center gap-2 font-semibold text-slate-900">
				<Download class="h-5 w-5 text-monaco-600" />
				Export Reports
			</h2>
			<p class="mt-1 text-sm text-slate-500">Download detailed reports as CSV files</p>
		</div>

		<div class="grid gap-4 sm:grid-cols-3">
			<form
				method="POST"
				action="?/exportMembers"
				use:enhance={() => {
					isExporting = 'members';
					return async ({ update }) => {
						isExporting = null;
						await update();
					};
				}}
			>
				<button
					type="submit"
					disabled={isExporting === 'members'}
					class="flex w-full items-center justify-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-3 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
				>
					{#if isExporting === 'members'}
						<div class="h-4 w-4 animate-spin rounded-full border-2 border-slate-400 border-t-transparent"></div>
					{:else}
						<FileSpreadsheet class="h-4 w-4" />
					{/if}
					All Members Report
				</button>
			</form>

			<form
				method="POST"
				action="?/exportPayments"
				use:enhance={() => {
					isExporting = 'payments';
					return async ({ update }) => {
						isExporting = null;
						await update();
					};
				}}
			>
				<button
					type="submit"
					disabled={isExporting === 'payments'}
					class="flex w-full items-center justify-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-3 text-sm font-medium text-slate-700 hover:bg-slate-50 disabled:opacity-50"
				>
					{#if isExporting === 'payments'}
						<div class="h-4 w-4 animate-spin rounded-full border-2 border-slate-400 border-t-transparent"></div>
					{:else}
						<FileSpreadsheet class="h-4 w-4" />
					{/if}
					Payment History
				</button>
			</form>

			<form
				method="POST"
				action="?/exportOverdue"
				use:enhance={() => {
					isExporting = 'overdue';
					return async ({ update }) => {
						isExporting = null;
						await update();
					};
				}}
			>
				<button
					type="submit"
					disabled={isExporting === 'overdue'}
					class="flex w-full items-center justify-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm font-medium text-red-700 hover:bg-red-100 disabled:opacity-50"
				>
					{#if isExporting === 'overdue'}
						<div class="h-4 w-4 animate-spin rounded-full border-2 border-red-400 border-t-transparent"></div>
					{:else}
						<AlertCircle class="h-4 w-4" />
					{/if}
					Overdue Members
				</button>
			</form>
		</div>
	</div>
</div>
