<script lang="ts">
	import { goto } from '$app/navigation';
	import { Button } from '$lib/components/ui/button';
	import {
		FileText,
		Download,
		Users,
		DollarSign,
		Calendar,
		BarChart3,
		PieChart
	} from 'lucide-svelte';

	let { data } = $props();
	const {
		reportType,
		year,
		availableYears,
		members,
		payments,
		events,
		membershipStats,
		duesStats,
		eventStats
	} = data;

	function changeReport(type: string) {
		goto(`?type=${type}&year=${year}`);
	}

	function changeYear(newYear: number) {
		goto(`?type=${reportType}&year=${newYear}`);
	}

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

	function formatDate(dateString: string): string {
		return new Date(dateString).toLocaleDateString('en-US', {
			month: 'short',
			day: 'numeric',
			year: 'numeric'
		});
	}

	function exportToCsv(reportType: string) {
		let csvContent = '';
		let filename = '';

		switch (reportType) {
			case 'membership':
				csvContent = 'Member ID,First Name,Last Name,Email,Status,Role,Dues Status,Member Since\n';
				for (const member of members) {
					csvContent += `"${member.member_id}","${member.first_name}","${member.last_name}","${member.email}","${member.status_display_name || ''}","${member.role}","${member.dues_status}","${member.member_since}"\n`;
				}
				filename = `membership-report-${year}.csv`;
				break;

			case 'dues':
				csvContent = 'Date,Member,Amount,Method,Reference\n';
				for (const payment of payments) {
					csvContent += `"${payment.payment_date}","${payment.member?.first_name} ${payment.member?.last_name}","${payment.amount}","${payment.payment_method}","${payment.reference || ''}"\n`;
				}
				filename = `dues-report-${year}.csv`;
				break;

			case 'events':
				csvContent = 'Date,Event,Type,Attendees,Max Capacity,Waitlist\n';
				for (const event of events) {
					csvContent += `"${event.start_datetime}","${event.title}","${event.event_type_name || 'General'}","${event.total_attendees}","${event.max_attendees || 'Unlimited'}","${event.waitlist_count}"\n`;
				}
				filename = `events-report-${year}.csv`;
				break;
		}

		// Create and download
		const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
		const link = document.createElement('a');
		link.href = URL.createObjectURL(blob);
		link.download = filename;
		link.click();
	}

	const reportTabs = [
		{ id: 'membership', label: 'Membership', icon: Users },
		{ id: 'dues', label: 'Dues Collection', icon: DollarSign },
		{ id: 'events', label: 'Event Attendance', icon: Calendar }
	];
</script>

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

<div class="space-y-6">
	<!-- Page Header -->
	<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
		<div>
			<h1 class="text-2xl font-bold text-slate-900">Reports</h1>
			<p class="text-slate-500">Generate and export membership, dues, and event reports</p>
		</div>

		<div class="flex items-center gap-3">
			<!-- Year Selector -->
			<select
				value={year}
				onchange={(e) => changeYear(parseInt(e.currentTarget.value))}
				class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm focus:border-monaco-500 focus:outline-none focus:ring-2 focus:ring-monaco-500/20"
			>
				{#each availableYears as y}
					<option value={y}>{y}</option>
				{/each}
			</select>

			<!-- Export Button -->
			<Button variant="outline" onclick={() => exportToCsv(reportType)}>
				<Download class="mr-2 h-4 w-4" />
				Export CSV
			</Button>
		</div>
	</div>

	<!-- Report Type Tabs -->
	<div class="flex gap-2 border-b border-slate-200 pb-3">
		{#each reportTabs as tab}
			<button
				onclick={() => changeReport(tab.id)}
				class="flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors {reportType === tab.id
					? 'bg-monaco-600 text-white'
					: 'bg-slate-100 text-slate-600 hover:bg-slate-200'}"
			>
				<tab.icon class="h-4 w-4" />
				{tab.label}
			</button>
		{/each}
	</div>

	<!-- Membership Report -->
	{#if reportType === 'membership'}
		<div class="space-y-6">
			<!-- Stats Cards -->
			<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Total Members</p>
							<p class="mt-1 text-3xl font-bold text-slate-900">{membershipStats.total}</p>
						</div>
						<Users class="h-8 w-8 text-blue-500" />
					</div>
				</div>

				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Current Dues</p>
							<p class="mt-1 text-3xl font-bold text-green-600">{membershipStats.byDuesStatus.current}</p>
						</div>
						<BarChart3 class="h-8 w-8 text-green-500" />
					</div>
				</div>

				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Overdue</p>
							<p class="mt-1 text-3xl font-bold text-red-600">{membershipStats.byDuesStatus.overdue}</p>
						</div>
						<BarChart3 class="h-8 w-8 text-red-500" />
					</div>
				</div>

				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Never Paid</p>
							<p class="mt-1 text-3xl font-bold text-amber-600">{membershipStats.byDuesStatus.never_paid}</p>
						</div>
						<PieChart class="h-8 w-8 text-amber-500" />
					</div>
				</div>
			</div>

			<!-- Breakdown Cards -->
			<div class="grid gap-6 lg:grid-cols-2">
				<!-- By Role -->
				<div class="glass-card p-6">
					<h3 class="mb-4 font-semibold text-slate-900">Members by Role</h3>
					<div class="space-y-3">
						<div class="flex items-center justify-between">
							<span class="text-slate-600">Administrators</span>
							<span class="font-semibold">{membershipStats.byRole.admin}</span>
						</div>
						<div class="flex items-center justify-between">
							<span class="text-slate-600">Board Members</span>
							<span class="font-semibold">{membershipStats.byRole.board}</span>
						</div>
						<div class="flex items-center justify-between">
							<span class="text-slate-600">Regular Members</span>
							<span class="font-semibold">{membershipStats.byRole.member}</span>
						</div>
					</div>
				</div>

				<!-- By Status -->
				<div class="glass-card p-6">
					<h3 class="mb-4 font-semibold text-slate-900">Members by Status</h3>
					<div class="space-y-3">
						{#each Object.entries(membershipStats.byStatus) as [status, count]}
							<div class="flex items-center justify-between">
								<span class="text-slate-600">{status}</span>
								<span class="font-semibold">{count}</span>
							</div>
						{/each}
					</div>
				</div>
			</div>

			<!-- Member List -->
			<div class="glass-card overflow-hidden">
				<div class="border-b border-slate-200 bg-slate-50 px-6 py-3">
					<h3 class="font-semibold text-slate-900">All Members ({members.length})</h3>
				</div>
				<div class="overflow-x-auto">
					<table class="w-full text-sm">
						<thead class="bg-slate-50 text-left text-slate-500">
							<tr>
								<th class="px-6 py-3 font-medium">Member</th>
								<th class="px-6 py-3 font-medium">ID</th>
								<th class="px-6 py-3 font-medium">Status</th>
								<th class="px-6 py-3 font-medium">Dues</th>
								<th class="px-6 py-3 font-medium">Since</th>
							</tr>
						</thead>
						<tbody class="divide-y divide-slate-100">
							{#each members.slice(0, 20) as member}
								<tr class="hover:bg-slate-50">
									<td class="px-6 py-3">
										<div>
											<p class="font-medium text-slate-900">{member.first_name} {member.last_name}</p>
											<p class="text-xs text-slate-500">{member.email}</p>
										</div>
									</td>
									<td class="px-6 py-3 text-slate-600">{member.member_id}</td>
									<td class="px-6 py-3">
										<span class="rounded-full px-2 py-0.5 text-xs font-medium"
											style="background-color: {member.status_color}20; color: {member.status_color}">
											{member.status_display_name || 'Unknown'}
										</span>
									</td>
									<td class="px-6 py-3">
										<span class="rounded-full px-2 py-0.5 text-xs font-medium {
											member.dues_status === 'current' ? 'bg-green-100 text-green-700' :
											member.dues_status === 'due_soon' ? 'bg-amber-100 text-amber-700' :
											member.dues_status === 'overdue' ? 'bg-red-100 text-red-700' :
											'bg-slate-100 text-slate-700'
										}">
											{member.dues_status.replace('_', ' ')}
										</span>
									</td>
									<td class="px-6 py-3 text-slate-600">{formatDate(member.member_since)}</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
				{#if members.length > 20}
					<div class="border-t border-slate-200 bg-slate-50 px-6 py-3 text-center text-sm text-slate-500">
						Showing 20 of {members.length} members. Export CSV for full list.
					</div>
				{/if}
			</div>
		</div>
	{/if}

	<!-- Dues Collection Report -->
	{#if reportType === 'dues'}
		<div class="space-y-6">
			<!-- Stats Cards -->
			<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Total Collected ({year})</p>
							<p class="mt-1 text-3xl font-bold text-green-600">{formatCurrency(duesStats.totalCollected)}</p>
						</div>
						<DollarSign class="h-8 w-8 text-green-500" />
					</div>
				</div>

				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Payments</p>
							<p class="mt-1 text-3xl font-bold text-slate-900">{duesStats.paymentCount}</p>
						</div>
						<FileText class="h-8 w-8 text-blue-500" />
					</div>
				</div>

				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Avg. Payment</p>
							<p class="mt-1 text-3xl font-bold text-slate-900">
								{formatCurrency(duesStats.paymentCount > 0 ? duesStats.totalCollected / duesStats.paymentCount : 0)}
							</p>
						</div>
						<BarChart3 class="h-8 w-8 text-purple-500" />
					</div>
				</div>

				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Collection Rate</p>
							<p class="mt-1 text-3xl font-bold text-slate-900">
								{Math.round((membershipStats.byDuesStatus.current / membershipStats.total) * 100)}%
							</p>
						</div>
						<PieChart class="h-8 w-8 text-monaco-500" />
					</div>
				</div>
			</div>

			<!-- Breakdown Cards -->
			<div class="grid gap-6 lg:grid-cols-2">
				<!-- By Month -->
				<div class="glass-card p-6">
					<h3 class="mb-4 font-semibold text-slate-900">Collection by Month</h3>
					<div class="space-y-3">
						{#each Object.entries(duesStats.byMonth).slice(0, 12) as [month, data]}
							<div class="flex items-center justify-between">
								<span class="text-slate-600">{month}</span>
								<div class="text-right">
									<span class="font-semibold">{formatCurrency(data.amount)}</span>
									<span class="ml-2 text-sm text-slate-500">({data.count})</span>
								</div>
							</div>
						{/each}
					</div>
				</div>

				<!-- By Method -->
				<div class="glass-card p-6">
					<h3 class="mb-4 font-semibold text-slate-900">Collection by Payment Method</h3>
					<div class="space-y-3">
						{#each Object.entries(duesStats.byMethod) as [method, data]}
							<div class="flex items-center justify-between">
								<span class="text-slate-600 capitalize">{method.replace('_', ' ')}</span>
								<div class="text-right">
									<span class="font-semibold">{formatCurrency(data.amount)}</span>
									<span class="ml-2 text-sm text-slate-500">({data.count})</span>
								</div>
							</div>
						{/each}
					</div>
				</div>
			</div>

			<!-- Payment List -->
			<div class="glass-card overflow-hidden">
				<div class="border-b border-slate-200 bg-slate-50 px-6 py-3">
					<h3 class="font-semibold text-slate-900">All Payments ({payments.length})</h3>
				</div>
				<div class="overflow-x-auto">
					<table class="w-full text-sm">
						<thead class="bg-slate-50 text-left text-slate-500">
							<tr>
								<th class="px-6 py-3 font-medium">Date</th>
								<th class="px-6 py-3 font-medium">Member</th>
								<th class="px-6 py-3 font-medium">Amount</th>
								<th class="px-6 py-3 font-medium">Method</th>
								<th class="px-6 py-3 font-medium">Reference</th>
							</tr>
						</thead>
						<tbody class="divide-y divide-slate-100">
							{#each payments.slice(0, 20) as payment}
								<tr class="hover:bg-slate-50">
									<td class="px-6 py-3 text-slate-600">{formatDate(payment.payment_date)}</td>
									<td class="px-6 py-3">
										<p class="font-medium text-slate-900">{payment.member?.first_name} {payment.member?.last_name}</p>
									</td>
									<td class="px-6 py-3 font-semibold text-green-600">{formatCurrency(payment.amount)}</td>
									<td class="px-6 py-3 text-slate-600 capitalize">{payment.payment_method?.replace('_', ' ')}</td>
									<td class="px-6 py-3 text-slate-500">{payment.reference || '-'}</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
				{#if payments.length > 20}
					<div class="border-t border-slate-200 bg-slate-50 px-6 py-3 text-center text-sm text-slate-500">
						Showing 20 of {payments.length} payments. Export CSV for full list.
					</div>
				{/if}
			</div>
		</div>
	{/if}

	<!-- Event Attendance Report -->
	{#if reportType === 'events'}
		<div class="space-y-6">
			<!-- Stats Cards -->
			<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Total Events ({year})</p>
							<p class="mt-1 text-3xl font-bold text-slate-900">{eventStats.totalEvents}</p>
						</div>
						<Calendar class="h-8 w-8 text-monaco-500" />
					</div>
				</div>

				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Total Attendees</p>
							<p class="mt-1 text-3xl font-bold text-blue-600">{eventStats.totalAttendees}</p>
						</div>
						<Users class="h-8 w-8 text-blue-500" />
					</div>
				</div>

				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Avg. Attendance</p>
							<p class="mt-1 text-3xl font-bold text-slate-900">{eventStats.averageAttendance}</p>
						</div>
						<BarChart3 class="h-8 w-8 text-purple-500" />
					</div>
				</div>

				<div class="glass-card p-6">
					<div class="flex items-center justify-between">
						<div>
							<p class="text-sm text-slate-500">Event Types</p>
							<p class="mt-1 text-3xl font-bold text-slate-900">{Object.keys(eventStats.byType).length}</p>
						</div>
						<PieChart class="h-8 w-8 text-amber-500" />
					</div>
				</div>
			</div>

			<!-- Breakdown by Type -->
			<div class="glass-card p-6">
				<h3 class="mb-4 font-semibold text-slate-900">Attendance by Event Type</h3>
				<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
					{#each Object.entries(eventStats.byType) as [type, data]}
						<div class="rounded-lg bg-slate-50 p-4">
							<p class="font-medium text-slate-900">{type}</p>
							<div class="mt-2 flex items-center justify-between text-sm">
								<span class="text-slate-500">{data.count} events</span>
								<span class="font-semibold text-blue-600">{data.attendees} attendees</span>
							</div>
						</div>
					{/each}
				</div>
			</div>

			<!-- Event List -->
			<div class="glass-card overflow-hidden">
				<div class="border-b border-slate-200 bg-slate-50 px-6 py-3">
					<h3 class="font-semibold text-slate-900">All Events ({events.length})</h3>
				</div>
				<div class="overflow-x-auto">
					<table class="w-full text-sm">
						<thead class="bg-slate-50 text-left text-slate-500">
							<tr>
								<th class="px-6 py-3 font-medium">Date</th>
								<th class="px-6 py-3 font-medium">Event</th>
								<th class="px-6 py-3 font-medium">Type</th>
								<th class="px-6 py-3 font-medium">Attendees</th>
								<th class="px-6 py-3 font-medium">Capacity</th>
								<th class="px-6 py-3 font-medium">Waitlist</th>
							</tr>
						</thead>
						<tbody class="divide-y divide-slate-100">
							{#each events.slice(0, 20) as event}
								<tr class="hover:bg-slate-50">
									<td class="px-6 py-3 text-slate-600">{formatDate(event.start_datetime)}</td>
									<td class="px-6 py-3 font-medium text-slate-900">{event.title}</td>
									<td class="px-6 py-3">
										<span class="rounded-full px-2 py-0.5 text-xs font-medium"
											style="background-color: {event.event_type_color}20; color: {event.event_type_color}">
											{event.event_type_name || 'General'}
										</span>
									</td>
									<td class="px-6 py-3 font-semibold text-blue-600">{event.total_attendees}</td>
									<td class="px-6 py-3 text-slate-600">{event.max_attendees || 'Unlimited'}</td>
									<td class="px-6 py-3 text-slate-600">{event.waitlist_count}</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
				{#if events.length > 20}
					<div class="border-t border-slate-200 bg-slate-50 px-6 py-3 text-center text-sm text-slate-500">
						Showing 20 of {events.length} events. Export CSV for full list.
					</div>
				{/if}
			</div>
		</div>
	{/if}
</div>
