<script>
	import Modal from '$lib/components/Modal.svelte';
	import UserEditForm from '$lib/components/UserEditForm.svelte';
	import SubscriptionEditForm from '$lib/components/SubscriptionEditForm.svelte';
	import InputField from '$lib/components/InputField.svelte';
	import { t } from 'svelte-i18n';
	import { page } from '$app/stores';
	import { applyAction, enhance } from '$app/forms';
	import { receive, send } from '$lib/utils/helpers';

	/** @type {import('./$types').ActionData} */
	export let form;

	$: ({
		user = [],
		users = [],
		licence_categories = [],
		subscriptions = [],
		payments = []
	} = $page.data);

	let activeSection = 'users';
	/** @type{App.Locals['user'] | null} */
	let selectedUser = null;
	/** @type{App.Types['subscription'] | null} */
	let selectedSubscription = null;
	let showSubscriptionModal = false;
	let showUserModal = false;
	let searchTerm = '';

	$: filteredUsers = searchTerm ? getFilteredUsers() : users;

	function handleMailButtonClick() {
		const subject = 'Important Announcement';
		const body = `Hello everyone,\n\nThis is an important message.`;
		const bccEmails = filteredUsers
			.map((/** @type{App.Locals['user']}*/ user) => user.email)
			.join(',');
		const encodedSubject = encodeURIComponent(subject);
		const encodedBody = encodeURIComponent(body);
		const mailtoLink = `mailto:?bcc=${bccEmails}&subject=${encodedSubject}&body=${encodedBody}`;
		window.location.href = mailtoLink; // Open the mail client
	}

	/**
	 * returns a set of users depending on the entered search query
	 * @return {App.Locals['user'][]}*/
	const getFilteredUsers = () => {
		if (!searchTerm.trim()) return users;

		const term = searchTerm.trim().toLowerCase();

		return users.filter((/** @type{App.Locals['user']}*/ user) => {
			const basicMatch = [
				user.first_name?.toLowerCase(),
				user.last_name?.toLowerCase(),
				user.email?.toLowerCase(),
				user.address?.toLowerCase(),
				user.city?.toLowerCase(),
				user.dateofbirth?.toLowerCase(),
				user.phone?.toLowerCase(),
				user.company?.toLowerCase(),
				user.licence?.number?.toLowerCase()
			].some((field) => field?.includes(term));

			const subscriptionMatch = user.membership?.subscription_model?.name
				?.toLowerCase()
				.includes(term);

			const licenceCategoryMatch = user.licence?.categories?.some((cat) =>
				cat.category.toLowerCase().includes(term)
			);

			const addressMatch = [
				user.address?.toLowerCase(),
				user.zip_code?.toLowerCase(),
				user.city?.toLowerCase()
			].some((field) => field?.includes(term));
			return basicMatch || subscriptionMatch || licenceCategoryMatch || addressMatch;
		});
	};

	/**
	 * Opens the edit modal for the selected user.
	 * @param {App.Locals['user'] | null} user The user to edit.
	 */
	const openEditUserModal = (user) => {
		selectedUser = user;
		showUserModal = true;
	};

	/**
	 * Opens the edit modal for the selected subscription.
	 * @param {App.Types['subscription'] | null} subscription The user to edit.
	 */
	const openEditSubscriptionModal = (subscription) => {
		selectedSubscription = subscription;
		showSubscriptionModal = true;
	};

	const close = () => {
		showUserModal = false;
		showSubscriptionModal = false;
		selectedUser = null;
		selectedSubscription = null;
		if (form) {
			form.errors = [];
		}
	};

	/**
	 * sets the active admin section for display
	 * @param {string} section The new active section.
	 */
	const setActiveSection = (section) => {
		activeSection = section;
	};
</script>

<div class="container">
	<div class="layout">
		<!-- Sidebar -->
		<nav class="sidebar">
			<ul class="nav-list">
				<li>
					<button
						class="nav-link {activeSection === 'users' ? 'active' : ''}"
						on:click={() => setActiveSection('users')}
					>
						<i class="fas fa-users"></i>
						{$t('users')}
						<span class="nav-badge">{users.length}</span>
					</button>
				</li>
				<li>
					<button
						class="nav-link {activeSection === 'subscriptions' ? 'active' : ''}"
						on:click={() => setActiveSection('subscriptions')}
					>
						<i class="fas fa-clipboard-list"></i>
						{$t('subscription.subscriptions')}
						<span class="nav-badge">{subscriptions.length}</span>
					</button>
				</li>
				<li>
					<button
						class="nav-link {activeSection === 'payments' ? 'active' : ''}"
						on:click={() => setActiveSection('payments')}
					>
						<i class="fas fa-credit-card"></i>
						{$t('payments')}
					</button>
				</li>
			</ul>
		</nav>

		<!-- Main Content -->
		<main class="main-content">
			{#if form?.errors}
				{#each form?.errors as error (error.id)}
					<h4
						class="step-subtitle warning"
						in:receive|global={{ key: error.id }}
						out:send|global={{ key: error.id }}
					>
						{$t(error.field) + ': ' + $t(error.key)}
					</h4>
				{/each}
			{/if}

			{#if activeSection === 'users'}
				<div class="section-header">
					<h2>{$t('users')}</h2>
					<div class="title-container">
						<InputField
							name="search"
							bind:value={searchTerm}
							placeholder={$t('placeholder.search')}
							backgroundColor="--base"
						/>
					</div>
					<!-- <input type="text" bind:value={searchTerm} placeholder={$t('placeholder.search')} /> -->
					<div>
						<button
							class="btn primary"
							aria-label="Mail Users"
							on:click={() => handleMailButtonClick()}
						>
							<i class="fas fa-envelope"></i>
						</button>
					</div>
					<div>
						<button class="btn primary" on:click={() => openEditUserModal(null)}>
							<i class="fas fa-plus"></i>
							{$t('add_new')}
						</button>
					</div>
				</div>
				<div class="accordion">
					{#each filteredUsers as user}
						<details class="accordion-item">
							<summary class="accordion-header">
								{user.first_name}
								{user.last_name} - {user.email}
							</summary>
							<div class="accordion-content">
								<table class="table">
									<tbody>
										<tr>
											<th>{$t('user.id')}</th>
											<td>{user.id}</td>
										</tr>
										<tr>
											<th>{$t('user.name')}</th>
											<td>{user.first_name} {user.last_name}</td>
										</tr>
										<tr>
											<th>{$t('user.email')}</th>
											<td>{user.email}</td>
										</tr>
										<tr>
											<th>{$t('status')}</th>
											<td>{$t('userStatus.' + user.status)}</td>
										</tr>
									</tbody>
								</table>
								<div class="button-group">
									<button class="btn primary" on:click={() => openEditUserModal(user)}>
										<i class="fas fa-edit"></i>
										{$t('edit')}
									</button>
									<form
										method="POST"
										action="?/userDelete"
										use:enhance={() => {
											return async ({ result }) => {
												if (result.type === 'success' || result.type === 'redirect') {
													await applyAction(result);
												}
											};
										}}
										on:submit|preventDefault={(/** @type {SubmitEvent} */ e) => {
											if (
												!confirm(
													$t('dialog.user_deletion', {
														values: {
															firstname: user.first_name || '',
															lastname: user.last_name || ''
														}
													})
												)
											) {
												e.preventDefault(); // Cancel form submission if user declines
											}
										}}
									>
										<input type="hidden" name="user[id]" value={user.id} />
										<input type="hidden" name="user[last_name]" value={user.last_name} />
										<button class="btn danger" type="submit">
											<i class="fas fa-trash"></i>
											{$t('delete')}
										</button>
									</form>
								</div>
							</div>
						</details>
					{/each}
				</div>
			{:else if activeSection === 'subscriptions'}
				<div class="section-header">
					<h2>{$t('subscription.subscriptions')}</h2>
					{#if user.role_id == 8}
						<button class="btn primary" on:click={() => openEditSubscriptionModal(null)}>
							<i class="fas fa-plus"></i>
							{$t('add_new')}
						</button>
					{/if}
				</div>
				<div class="accordion">
					{#each subscriptions as subscription}
						<details class="accordion-item">
							<summary class="accordion-header">
								{subscription.name}
							</summary>
							<div class="accordion-content">
								<table class="table">
									<tbody>
										<tr>
											<th>{$t('subscription.monthly_fee')}</th>
											<td
												>{subscription.monthly_fee !== -1
													? subscription.monthly_fee + '€'
													: '-'}</td
											>
										</tr>
										<tr>
											<th>{$t('subscription.hourly_rate')}</th>
											<td
												>{subscription.hourly_rate !== -1
													? subscription.hourly_rate + '€'
													: '-'}</td
											>
										</tr>
										<tr>
											<th>{$t('subscription.included_hours_per_year')}</th>
											<td>{subscription.included_hours_per_year || 0}</td>
										</tr>
										<tr>
											<th>{$t('subscription.included_hours_per_month')}</th>
											<td>{subscription.included_hours_per_month || 0}</td>
										</tr>
										<tr>
											<th>{$t('details')}</th>
											<td>{subscription.details || '-'}</td>
										</tr>
										<tr>
											<th>{$t('subscription.conditions')}</th>
											<td>{subscription.conditions || '-'}</td>
										</tr>
									</tbody>
								</table>
								{#if user.role_id == 8}
									<div class="button-group">
										<button
											class="btn primary"
											on:click={() => openEditSubscriptionModal(subscription)}
										>
											<i class="fas fa-edit"></i>
											{$t('edit')}
										</button>
										{#if !users.some(/** @param{App.Locals['user']} user */ (user) => user.membership?.subscription_model?.id === subscription.id)}
											<form
												method="POST"
												action="?/subscriptionDelete"
												use:enhance={() => {
													return async ({ result }) => {
														if (result.type === 'success' || result.type === 'redirect') {
															await applyAction(result);
														} else {
															document
																.querySelector('.accordion-content')
																?.scrollTo({ top: 0, behavior: 'smooth' });
															await applyAction(result);
														}
													};
												}}
												on:submit|preventDefault={(/** @type {SubmitEvent} */ e) => {
													if (
														!confirm(
															$t('dialog.subscription_deletion', {
																values: {
																	name: subscription.name || ''
																}
															})
														)
													) {
														e.preventDefault(); // Cancel form submission if user declines
													}
												}}
											>
												<input type="hidden" name="subscription[id]" value={subscription.id} />
												<input type="hidden" name="subscription[name]" value={subscription.name} />
												<button class="btn danger" type="submit">
													<i class="fas fa-trash"></i>
													{$t('delete')}
												</button>
											</form>
										{/if}
									</div>
								{/if}
							</div>
						</details>
					{/each}
				</div>
			{:else if activeSection === 'payments'}
				<h2>{$t('payments')}</h2>
				<div class="accordion">
					{#each payments as payment}
						<details class="accordion-item">
							<summary class="accordion-header">
								Payment #{payment.id} - {payment.amount}€
							</summary>
							<div class="accordion-content">
								<table class="table">
									<tbody>
										<tr>
											<th>Date</th>
											<td>{new Date(payment.date).toLocaleDateString()}</td>
										</tr>
										<tr>
											<th>Status</th>
											<td>{payment.status}</td>
										</tr>
									</tbody>
								</table>
							</div>
						</details>
					{/each}
				</div>
			{/if}
		</main>
	</div>
</div>

{#if showUserModal}
	<Modal on:close={close}>
		<UserEditForm
			{form}
			user={selectedUser}
			{subscriptions}
			{licence_categories}
			on:cancel={close}
			on:close={close}
		/>
	</Modal>
{:else if showSubscriptionModal}
	<Modal on:close={close}>
		<SubscriptionEditForm
			{form}
			{user}
			subscription={selectedSubscription}
			on:cancel={close}
			on:close={close}
		/>
	</Modal>
{/if}

<style>
	.title-container {
		margin: 0 1rem;
		flex-grow: 1;
		max-width: 500px;
	}

	.section-header {
		display: flex;
		align-items: center;
		gap: 1rem;
		margin-bottom: 1rem;
	}
	.container {
		width: 100%;
		height: 100%;
		padding: 0 1rem;
		color: var(--text);
	}

	.layout {
		display: grid;
		grid-template-columns: 250px 1fr;
		gap: 2rem;
		height: 100%;
		width: inherit;
	}

	.sidebar {
		width: 250px;
		background: var(--surface0);
		border-right: 1px solid var(--surface1);
	}

	.nav-list {
		list-style: none;
		padding: 0;
		margin: 0;
	}

	.nav-link {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		width: 100%;
		padding: 0.75rem 1rem;
		border: none;
		background: none;
		text-align: left;
		cursor: pointer;
		color: var(--subtext0);
		text-transform: uppercase;
		font-weight: 500;
		letter-spacing: 1px;
		transition: color 0.3s ease-in-out;
	}

	.nav-link:hover {
		background: var(--surface1);
		color: var(--text);
	}

	.nav-link.active {
		background: var(--surface2);
		color: var(--lavender);
		border-left: 3px solid var(--mauve);
	}

	.main-content {
		padding: 2rem;
		min-width: 75%;
	}

	.accordion-item {
		border: none;
		background: var(--surface0);
		margin-bottom: 0.5rem;
		border-radius: 8px;
		overflow: hidden;
	}

	.accordion-header {
		padding: 1rem;
		cursor: pointer;
		font-family: 'Roboto Mono', monospace;
		color: var(--text);
		background: var(--surface1);
		transition: background-color 0.2s ease-in-out;
	}

	.accordion-header:hover {
		background: var(--surface2);
	}

	.accordion-content {
		padding: 1rem;
		background: var(--surface0);
		border-top: 1px solid var(--surface1);
	}

	.table {
		width: 100%;
		border-collapse: collapse;
		font-family: 'Roboto Mono', monospace;
	}

	.table th,
	.table td {
		padding: 0.75rem;
		border-bottom: 1px solid #2f2f2f;
		text-align: left;
	}

	.table th {
		color: var(--subtext1);
	}

	.table td {
		color: var(--text);
	}

	@media (max-width: 680px) {
		.layout {
			grid-template-columns: 1fr;
		}

		.sidebar {
			position: static;
			width: 100%;
			padding: 1rem 0;
		}

		.main-content {
			margin-left: 0;
			margin-top: 120px;
		}
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 2rem;
	}

	.section-header h2 {
		margin: 0;
		color: var(--lavender);
	}
	/* Additional styles for better visual hierarchy */
	details[open] .accordion-header {
		background: var(--surface2);
		color: var(--lavender);
	}

	.button-group {
		margin-top: 1rem;
		display: flex;
		gap: 0.5rem;
	}

	/* Style for the nav badge */
	.nav-badge {
		background: var(--surface2);
		color: var(--text);
		padding: 0.2rem 0.5rem;
		border-radius: 4px;
		font-size: 0.8rem;
		margin-left: auto;
	}

	/* Improved focus states */
	.nav-link:focus,
	.accordion-header:focus {
		outline: 2px solid var(--mauve);
		outline-offset: -2px;
		border-radius: 8px;
	}

	/* Add subtle transitions */
	.accordion-item,
	.accordion-header,
	.nav-link {
		transition: all 0.2s ease-in-out;
	}
</style>
