<script lang="ts">
	import { onMount } from "svelte";
	import { pageTitle } from "$lib/hooks/page-title.svelte";
	import Container from "$lib/components/atoms/container.svelte";
	import Title from "$lib/components/atoms/title.svelte";
	import { Button } from "$lib/components/ui/button";
	import { Input } from "$lib/components/ui/input";
	import { Checkbox } from "$lib/components/ui/checkbox";
	import { sessionHistoryVM } from "$lib/domains/ckflow/session-history.vm.svelte";
	import SessionHistoryList from "$lib/domains/ckflow/view/session-history-list.svelte";
	import SessionHistoryDetailModal from "$lib/domains/ckflow/view/session-history-detail-modal.svelte";
	import { Label } from "$lib/components/ui/label";
	import Icon from "$lib/components/atoms/icon.svelte";
	import { toast } from "svelte-sonner";

	// Icons
	import RefreshIcon from "~icons/solar/refresh-linear";

	pageTitle.set("Session History");

	let modalOpen = $state(false);
	let searchQuery = $state("");

	async function handleSoftDelete(flowId: string) {
		const result = await sessionHistoryVM.softDeleteSession(flowId);
		if (result?.error) {
			toast.error(result.error.message, {
				description: result.error.detail,
			});
		} else {
			toast.success("Session deleted successfully");
		}
	}

	async function handleRestore(flowId: string) {
		const result = await sessionHistoryVM.restoreSession(flowId);
		if (result?.error) {
			toast.error(result.error.message, {
				description: result.error.detail,
			});
		} else {
			toast.success("Session restored successfully");
		}
	}

	function closeModal() {
		modalOpen = false;
		sessionHistoryVM.resetSelection();
	}

	function viewSessionDetail(session: any) {
		sessionHistoryVM.chosenSession = session;
		modalOpen = true;
	}

	function handleRefresh() {
		sessionHistoryVM.loadSessions();
	}

	$effect(() => {
		if (sessionHistoryVM.chosenSession) {
			modalOpen = true;
		}
	});

	// Filter sessions based on search query
	let filteredSessions = $derived(
		sessionHistoryVM.currentPageSessions.filter((session) => {
			if (!searchQuery) return true;
			const query = searchQuery.toLowerCase();
			return (
				session.flowId.toLowerCase().includes(query) ||
				session.domain.toLowerCase().includes(query)
			);
		}),
	);

	onMount(() => {
		sessionHistoryVM.loadSessions();
	});
</script>

<main class="grid w-full place-items-center pb-12 md:p-8">
	<div class="mb-4 flex w-full max-w-[90vw] items-center justify-between">
		<Title>Session History</Title>

		<div class="flex items-center gap-2">
			<Button variant="outline" size="sm" onclick={handleRefresh}>
				<Icon icon={RefreshIcon} cls="mr-2 h-4 w-4" />
				Refresh
			</Button>
		</div>
	</div>

	<div
		class="mb-4 flex w-full max-w-[90vw] flex-col justify-between gap-4 md:flex-row"
	>
		<Input
			placeholder="Search by ID or domain..."
			class="max-w-sm"
			bind:value={searchQuery}
		/>

		<div class="flex items-center space-x-2">
			<Checkbox
				id="includeDeleted"
				checked={sessionHistoryVM.includeDeleted}
				onCheckedChange={() => sessionHistoryVM.toggleIncludeDeleted()}
			/>
			<Label for="includeDeleted">Include deleted sessions</Label>
		</div>
	</div>

	<Container
		containerClass="flex flex-col w-full h-full min-h-[44rem]"
		wrapperClass="max-w-[90vw]"
	>
		<SessionHistoryList
			sessions={filteredSessions}
			isLoading={sessionHistoryVM.isLoading}
			includeDeleted={sessionHistoryVM.includeDeleted}
			bind:selectedSession={sessionHistoryVM.chosenSession}
			onSoftDelete={handleSoftDelete}
			onRestore={handleRestore}
		/>

		<!-- Pagination -->
		<div class="mt-4 flex justify-center gap-2">
			<Button
				variant="outline"
				size="sm"
				disabled={sessionHistoryVM.currentPage === 1}
				onclick={() => sessionHistoryVM.prevPage()}
			>
				Previous
			</Button>

			<div class="mx-2 flex items-center">
				<span class="text-sm">
					Page {sessionHistoryVM.currentPage} of {sessionHistoryVM.totalPages}
				</span>
			</div>

			<Button
				variant="outline"
				size="sm"
				disabled={sessionHistoryVM.currentPage ===
					sessionHistoryVM.totalPages}
				onclick={() => sessionHistoryVM.nextPage()}
			>
				Next
			</Button>
		</div>
	</Container>

	<!-- Session Detail Modal -->
	<SessionHistoryDetailModal
		session={sessionHistoryVM.chosenSession}
		open={modalOpen}
		onClose={closeModal}
		onSoftDelete={handleSoftDelete}
		onRestore={handleRestore}
	/>
</main>
