<script lang="ts">
	import {
		CreditCard,
		Search,
		Filter,
		ChevronDown,
		Plus,
		CheckCircle2,
		Clock,
		AlertCircle,
		XCircle,
		Calendar,
		DollarSign,
		Users,
		X,
		Mail,
		Send,
		FileText,
		Bell
	} from 'lucide-svelte';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { DatePicker } from '$lib/components/ui';
	import { CalendarDate, today, getLocalTimeZone } from '@internationalized/date';
	import { goto, invalidateAll } from '$app/navigation';
	import { page } from '$app/stores';
	import { enhance } from '$app/forms';

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

	// Use $derived to make these reactive when data updates after invalidateAll()
	const members = $derived(data.members);
	const selectedMember = $derived(data.selectedMember);
	const stats = $derived(data.stats);
	const recentPayments = $derived(data.recentPayments);
	const membershipTypes = $derived(data.membershipTypes);
	const filters = $derived(data.filters);

	let searchQuery = $state(filters.search);
	let statusFilter = $state(filters.status);
	let showFilters = $state(false);
	let showPaymentModal = $state(!!selectedMember);
	let selectedMemberForPayment = $state<any>(selectedMember);
	let isSubmitting = $state(false);

	// Bulk action state
	let showBulkModal = $state(false);
	let bulkActionType = $state<'dueSoon' | 'overdue' | null>(null);
	let isBulkSubmitting = $state(false);
	let bulkResult = $state<any>(null);

	// Individual reminder state
	let sendingReminderId = $state<string | null>(null);

	// Debounce search
	let searchTimeout: ReturnType<typeof setTimeout>;
	function handleSearch(value: string) {
		clearTimeout(searchTimeout);
		searchTimeout = setTimeout(() => {
			updateFilters({ search: value });
		}, 300);
	}

	function updateFilters(newFilters: Record<string, string>) {
		const params = new URLSearchParams($page.url.searchParams);
		for (const [key, value] of Object.entries(newFilters)) {
			if (value && value !== 'all') {
				params.set(key, value);
			} else {
				params.delete(key);
			}
		}
		goto(`?${params.toString()}`, { replaceState: true });
	}

	function openPaymentModal(member: any) {
		selectedMemberForPayment = member;
		showPaymentModal = true;
	}

	function closePaymentModal() {
		showPaymentModal = false;
		selectedMemberForPayment = null;
		// Remove member param from URL
		const params = new URLSearchParams($page.url.searchParams);
		params.delete('member');
		goto(`?${params.toString()}`, { replaceState: true });
	}

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

	// Get dues status info
	function getDuesInfo(status: string | null) {
		switch (status) {
			case 'current':
				return {
					icon: CheckCircle2,
					color: 'text-green-600',
					bg: 'bg-green-100',
					label: 'Current'
				};
			case 'due_soon':
				return { icon: Clock, color: 'text-yellow-600', bg: 'bg-yellow-100', label: 'Due Soon' };
			case 'overdue':
				return { icon: AlertCircle, color: 'text-red-600', bg: 'bg-red-100', label: 'Overdue' };
			case 'never_paid':
			default:
				return { icon: XCircle, color: 'text-slate-500', bg: 'bg-slate-100', label: 'Never Paid' };
		}
	}

	// Get default amount based on membership type
	function getDefaultAmount(member: any): number {
		return member?.annual_dues || 50;
	}

	// Today's date for default payment date
	const todayDate = today(getLocalTimeZone());
	let paymentDate = $state<CalendarDate | undefined>(todayDate);

	// Reset payment date when modal opens
	function openPaymentModalWithReset(member: any) {
		paymentDate = todayDate;
		openPaymentModal(member);
	}

	// Bulk actions
	function openBulkModal(type: 'dueSoon' | 'overdue') {
		bulkActionType = type;
		bulkResult = null;
		showBulkModal = true;
	}

	function closeBulkModal() {
		showBulkModal = false;
		bulkActionType = null;
		bulkResult = null;
	}
</script>

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

<div class="space-y-6">
	<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">Dues Management</h1>
			<p class="text-slate-500">Track and record membership dues payments</p>
		</div>
		<div class="flex flex-wrap gap-2">
			<a
				href="/board/dues/reports"
				class="flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50"
			>
				<FileText class="h-4 w-4" />
				Reports
			</a>
			<button
				onclick={() => openBulkModal('dueSoon')}
				disabled={stats.dueSoon === 0}
				class="flex items-center gap-1.5 rounded-lg border border-yellow-200 bg-yellow-50 px-3 py-1.5 text-sm font-medium text-yellow-700 hover:bg-yellow-100 disabled:cursor-not-allowed disabled:opacity-50"
			>
				<Bell class="h-4 w-4" />
				Remind Due Soon ({stats.dueSoon})
			</button>
			<button
				onclick={() => openBulkModal('overdue')}
				disabled={stats.overdue === 0}
				class="flex items-center gap-1.5 rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-sm font-medium text-red-700 hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-50"
			>
				<AlertCircle class="h-4 w-4" />
				Remind Overdue ({stats.overdue})
			</button>
		</div>
	</div>

	<!-- Stats Cards -->
	<div class="grid grid-cols-2 gap-4 sm:grid-cols-5">
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-slate-100 p-2">
					<Users class="h-5 w-5 text-slate-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.total}</p>
					<p class="text-xs text-slate-500">Total</p>
				</div>
			</div>
		</div>
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-green-100 p-2">
					<CheckCircle2 class="h-5 w-5 text-green-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.current}</p>
					<p class="text-xs text-slate-500">Current</p>
				</div>
			</div>
		</div>
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-yellow-100 p-2">
					<Clock class="h-5 w-5 text-yellow-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.dueSoon}</p>
					<p class="text-xs text-slate-500">Due Soon</p>
				</div>
			</div>
		</div>
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-red-100 p-2">
					<AlertCircle class="h-5 w-5 text-red-600" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.overdue}</p>
					<p class="text-xs text-slate-500">Overdue</p>
				</div>
			</div>
		</div>
		<div class="glass-card p-4">
			<div class="flex items-center gap-3">
				<div class="rounded-lg bg-slate-100 p-2">
					<XCircle class="h-5 w-5 text-slate-500" />
				</div>
				<div>
					<p class="text-2xl font-bold text-slate-900">{stats.neverPaid}</p>
					<p class="text-xs text-slate-500">Never Paid</p>
				</div>
			</div>
		</div>
	</div>

	<div class="grid gap-6 lg:grid-cols-3">
		<!-- Members List -->
		<div class="lg:col-span-2">
			<div class="glass-card overflow-hidden">
				<div class="border-b border-slate-200 p-4">
					<div class="flex flex-col gap-4 sm:flex-row sm:items-center">
						<div class="relative flex-1">
							<Search class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
							<Input
								type="search"
								placeholder="Search members..."
								value={searchQuery}
								oninput={(e) => {
									searchQuery = e.currentTarget.value;
									handleSearch(e.currentTarget.value);
								}}
								class="h-10 pl-9"
							/>
						</div>

						<select
							bind:value={statusFilter}
							onchange={() => updateFilters({ status: statusFilter })}
							class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
						>
							<option value="all">All Status</option>
							<option value="current">Current</option>
							<option value="due_soon">Due Soon</option>
							<option value="overdue">Overdue</option>
							<option value="never_paid">Never Paid</option>
						</select>
					</div>
				</div>

				{#if members.length === 0}
					<div class="flex flex-col items-center justify-center p-12 text-center">
						<CreditCard class="mb-4 h-16 w-16 text-slate-300" />
						<h3 class="text-lg font-medium text-slate-900">No members found</h3>
						<p class="mt-1 text-slate-500">Try adjusting your search or filters.</p>
					</div>
				{:else}
					<div class="divide-y divide-slate-100">
						{#each members as member}
							{@const duesInfo = getDuesInfo(member.dues_status)}
							<div class="flex items-center justify-between p-4 hover:bg-slate-50">
								<div class="flex items-center gap-3">
									{#if member.avatar_url}
										<img
											src={member.avatar_url}
											alt=""
											class="h-10 w-10 rounded-full object-cover"
										/>
									{:else}
										<div
											class="flex h-10 w-10 items-center justify-center rounded-full bg-monaco-100 text-monaco-700"
										>
											{member.first_name?.[0]}{member.last_name?.[0]}
										</div>
									{/if}
									<div>
										<p class="font-medium text-slate-900">
											{member.first_name} {member.last_name}
										</p>
										<p class="text-xs text-slate-500">{member.member_id}</p>
									</div>
								</div>

								<div class="flex items-center gap-2 sm:gap-4">
									<div class="text-right">
										<span
											class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium {duesInfo.bg} {duesInfo.color}"
										>
											<svelte:component this={duesInfo.icon} class="h-3 w-3" />
											{duesInfo.label}
										</span>
										{#if member.current_due_date}
											<p class="mt-0.5 text-xs text-slate-500">
												{member.dues_status === 'overdue'
													? `${member.days_overdue} days overdue`
													: `Due: ${formatDate(member.current_due_date)}`}
											</p>
										{/if}
									</div>

									{#if member.dues_status !== 'current' && member.dues_status !== 'never_paid'}
										<form
											method="POST"
											action="?/sendReminder"
											use:enhance={() => {
												sendingReminderId = member.id;
												return async ({ update }) => {
													sendingReminderId = null;
													await update();
													await invalidateAll();
												};
											}}
										>
											<input type="hidden" name="member_id" value={member.id} />
											<button
												type="submit"
												disabled={sendingReminderId === member.id}
												title="Send Reminder Email"
												class="flex items-center gap-1.5 rounded-lg border {member.dues_status === 'overdue' ? 'border-red-200 bg-red-50 text-red-600 hover:bg-red-100' : 'border-yellow-200 bg-yellow-50 text-yellow-600 hover:bg-yellow-100'} px-2.5 py-1.5 text-sm font-medium disabled:opacity-50"
											>
												{#if sendingReminderId === member.id}
													<div class="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"></div>
													<span class="hidden sm:inline">Sending...</span>
												{:else}
													<Mail class="h-4 w-4" />
													<span class="hidden sm:inline">Remind</span>
												{/if}
											</button>
										</form>
									{/if}

									<button
										onclick={() => openPaymentModalWithReset(member)}
										class="flex items-center gap-1.5 rounded-lg bg-monaco-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-monaco-700"
									>
										<Plus class="h-4 w-4" />
										Record
									</button>
								</div>
							</div>
						{/each}
					</div>
				{/if}
			</div>
		</div>

		<!-- Recent Payments -->
		<div class="lg:col-span-1">
			<div class="glass-card overflow-hidden">
				<div class="border-b border-slate-200 px-4 py-3">
					<h2 class="flex items-center gap-2 font-semibold text-slate-900">
						<Calendar class="h-4 w-4 text-monaco-600" />
						Recent Payments
					</h2>
				</div>

				{#if recentPayments.length === 0}
					<div class="p-8 text-center">
						<p class="text-sm text-slate-500">No payments recorded yet.</p>
					</div>
				{:else}
					<div class="divide-y divide-slate-100">
						{#each recentPayments as payment}
							<div class="p-4">
								<div class="flex items-center justify-between">
									<div>
										<p class="font-medium text-slate-900">
											{payment.member?.first_name} {payment.member?.last_name}
										</p>
										<p class="text-xs text-slate-500">{payment.member?.member_id}</p>
									</div>
									<p class="font-semibold text-slate-900">€{payment.amount.toFixed(2)}</p>
								</div>
								<div class="mt-2 flex items-center justify-between text-xs text-slate-500">
									<span>{formatDate(payment.payment_date)}</span>
									<span>by {payment.recorder?.first_name}</span>
								</div>
							</div>
						{/each}
					</div>
				{/if}
			</div>
		</div>
	</div>
</div>

<!-- Payment Recording Modal -->
{#if showPaymentModal && selectedMemberForPayment}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-6 flex items-center justify-between">
				<h2 class="text-lg font-semibold text-slate-900">Record Payment</h2>
				<button onclick={closePaymentModal} class="rounded p-1 hover:bg-slate-100">
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			<!-- Member Info -->
			<div class="mb-6 flex items-center gap-3 rounded-lg bg-slate-50 p-3">
				{#if selectedMemberForPayment.avatar_url}
					<img
						src={selectedMemberForPayment.avatar_url}
						alt=""
						class="h-12 w-12 rounded-full object-cover"
					/>
				{:else}
					<div
						class="flex h-12 w-12 items-center justify-center rounded-full bg-monaco-100 text-monaco-700"
					>
						{selectedMemberForPayment.first_name?.[0]}{selectedMemberForPayment.last_name?.[0]}
					</div>
				{/if}
				<div>
					<p class="font-medium text-slate-900">
						{selectedMemberForPayment.first_name} {selectedMemberForPayment.last_name}
					</p>
					<p class="text-sm text-slate-500">
						{selectedMemberForPayment.member_id} •
						{selectedMemberForPayment.membership_type_name || 'Regular Member'}
					</p>
				</div>
			</div>

			{#if form?.error}
				<div class="mb-4 rounded-lg bg-red-50 p-3 text-sm text-red-600">
					{form.error}
				</div>
			{/if}

			{#if form?.success}
				<div class="mb-4 rounded-lg bg-green-50 p-3 text-sm text-green-600">
					{form.success}
				</div>
			{/if}

			<form
				method="POST"
				action="?/recordPayment"
				use:enhance={() => {
					isSubmitting = true;
					return async ({ update, result }) => {
						isSubmitting = false;
						if (result.type === 'success') {
							await invalidateAll();
							setTimeout(closePaymentModal, 1500);
						}
						await update();
					};
				}}
				class="space-y-4"
			>
				<input type="hidden" name="member_id" value={selectedMemberForPayment.id} />

				<div>
					<Label for="amount">Amount (€)</Label>
					<Input
						type="number"
						id="amount"
						name="amount"
						step="0.01"
						value={getDefaultAmount(selectedMemberForPayment)}
						required
						class="mt-1"
					/>
				</div>

				<div>
					<Label>Payment Date</Label>
					<div class="mt-1">
						<DatePicker
							bind:value={paymentDate}
							maxValue={todayDate}
							placeholder="Select payment date"
							name="payment_date"
						/>
					</div>
				</div>

				<div>
					<Label for="payment_method">Payment Method</Label>
					<select
						id="payment_method"
						name="payment_method"
						class="mt-1 w-full rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm"
					>
						<option value="bank_transfer">Bank Transfer</option>
						<option value="cash">Cash</option>
						<option value="check">Check</option>
						<option value="other">Other</option>
					</select>
				</div>

				<div>
					<Label for="reference">Reference (optional)</Label>
					<Input
						type="text"
						id="reference"
						name="reference"
						placeholder="Transaction reference"
						class="mt-1"
					/>
				</div>

				<div>
					<Label for="notes">Notes (optional)</Label>
					<textarea
						id="notes"
						name="notes"
						rows="2"
						placeholder="Internal notes..."
						class="mt-1 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
					></textarea>
				</div>

				<div class="flex gap-3 pt-2">
					<button
						type="button"
						onclick={closePaymentModal}
						class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
					>
						Cancel
					</button>
					<button
						type="submit"
						disabled={isSubmitting}
						class="flex flex-1 items-center justify-center gap-2 rounded-lg bg-monaco-600 px-4 py-2 text-sm font-medium text-white hover:bg-monaco-700 disabled:opacity-50"
					>
						{#if isSubmitting}
							<div class="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"
							></div>
							Recording...
						{:else}
							<CreditCard class="h-4 w-4" />
							Record Payment
						{/if}
					</button>
				</div>
			</form>
		</div>
	</div>
{/if}

<!-- Bulk Action Modal -->
{#if showBulkModal && bulkActionType}
	<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
		<div class="glass-card w-full max-w-md p-6">
			<div class="mb-6 flex items-center justify-between">
				<h2 class="text-lg font-semibold text-slate-900">
					{bulkActionType === 'dueSoon' ? 'Send Due Soon Reminders' : 'Send Overdue Reminders'}
				</h2>
				<button onclick={closeBulkModal} class="rounded p-1 hover:bg-slate-100">
					<X class="h-5 w-5 text-slate-500" />
				</button>
			</div>

			{#if bulkResult}
				<!-- Results View -->
				<div class="space-y-4">
					<div class="rounded-lg bg-green-50 p-4">
						<p class="font-medium text-green-800">{bulkResult.success || bulkResult}</p>
					</div>
					<button
						onclick={closeBulkModal}
						class="w-full rounded-lg bg-slate-100 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-200"
					>
						Close
					</button>
				</div>
			{:else}
				<!-- Confirmation View -->
				<div class="space-y-4">
					<div class="rounded-lg {bulkActionType === 'dueSoon' ? 'bg-yellow-50 border-yellow-200' : 'bg-red-50 border-red-200'} border p-4">
						<div class="flex items-center gap-3">
							{#if bulkActionType === 'dueSoon'}
								<Clock class="h-8 w-8 text-yellow-600" />
							{:else}
								<AlertCircle class="h-8 w-8 text-red-600" />
							{/if}
							<div>
								<p class="font-medium {bulkActionType === 'dueSoon' ? 'text-yellow-800' : 'text-red-800'}">
									{bulkActionType === 'dueSoon' ? stats.dueSoon : stats.overdue} member(s) will receive reminders
								</p>
								<p class="text-sm {bulkActionType === 'dueSoon' ? 'text-yellow-600' : 'text-red-600'}">
									{bulkActionType === 'dueSoon'
										? 'Members with dues due within 30 days'
										: 'Members with overdue payments'}
								</p>
							</div>
						</div>
					</div>

					<p class="text-sm text-slate-600">
						This will send email reminders to all eligible members who haven't already received a reminder for their current dues period.
					</p>

					<form
						method="POST"
						action={bulkActionType === 'dueSoon' ? '?/sendBulkDueSoonReminders' : '?/sendBulkOverdueReminders'}
						use:enhance={() => {
							isBulkSubmitting = true;
							return async ({ result, update }) => {
								isBulkSubmitting = false;
								if (result.type === 'success' && result.data) {
									bulkResult = result.data;
									await invalidateAll();
								}
								await update();
							};
						}}
					>
						<div class="flex gap-3">
							<button
								type="button"
								onclick={closeBulkModal}
								class="flex-1 rounded-lg border border-slate-200 px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50"
							>
								Cancel
							</button>
							<button
								type="submit"
								disabled={isBulkSubmitting}
								class="flex flex-1 items-center justify-center gap-2 rounded-lg {bulkActionType === 'dueSoon' ? 'bg-yellow-600 hover:bg-yellow-700' : 'bg-red-600 hover:bg-red-700'} px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
							>
								{#if isBulkSubmitting}
									<div class="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"></div>
									Sending...
								{:else}
									<Send class="h-4 w-4" />
									Send Reminders
								{/if}
							</button>
						</div>
					</form>
				</div>
			{/if}
		</div>
	</div>
{/if}

<!-- Form Success/Error Toast -->
{#if form?.success && !showPaymentModal && !showBulkModal}
	<div class="fixed bottom-4 right-4 z-50 rounded-lg bg-green-50 border border-green-200 p-4 shadow-lg">
		<p class="text-sm font-medium text-green-800">{form.success}</p>
	</div>
{/if}

{#if form?.error && !showPaymentModal && !showBulkModal}
	<div class="fixed bottom-4 right-4 z-50 rounded-lg bg-red-50 border border-red-200 p-4 shadow-lg">
		<p class="text-sm font-medium text-red-800">{form.error}</p>
	</div>
{/if}
