<script lang="ts">
	import { afterNavigate, goto } from '$app/navigation';
	import { page } from '$app/state';
	import * as Tabs from '$lib/components/ui/tabs';
	import { ScrollText, ListTodo } from 'lucide-svelte';
	import * as m from '$lib/paraglide/messages.js';
	import BitacoraTab from './bitacora-tab.svelte';
	import TasksTab from './tasks-tab.svelte';
	import type { PageData } from './$types';

	let { data }: { data: PageData } = $props();

	let tabValue = $state(data.initialTab);

	$effect(() => {
		tabValue = data.initialTab;
	});

	afterNavigate(() => {
		const t = page.url.searchParams.get('tab') === 'tasks' ? 'tasks' : 'bitacora';
		tabValue = t;
	});

	function onTabValueChange(v: string) {
		const fromUrl = page.url.searchParams.get('tab') === 'tasks' ? 'tasks' : 'bitacora';
		if (v === fromUrl) return;

		const u = new URL(page.url.href);
		if (v === 'tasks') {
			u.searchParams.set('tab', 'tasks');
		} else {
			u.searchParams.delete('tab');
		}
		const qs = u.searchParams.toString();
		void goto(`${u.pathname}${qs ? `?${qs}` : ''}`, {
			replaceState: true,
			noScroll: true,
			keepFocus: true
		});
	}
</script>

<div class="container mx-auto flex min-h-[calc(100vh-85px)] flex-col space-y-6 py-6">
	<div class="flex items-center justify-between">
		<div>
			<h1 class="text-3xl font-bold tracking-tight">{m['sidebar.audit_logs_title']()}</h1>
			<p class="text-muted-foreground">{m['sidebar.audit_logs_description']()}</p>
		</div>
	</div>

	<Tabs.Root
		bind:value={tabValue}
		onValueChange={onTabValueChange}
		class="flex min-h-0 w-full flex-1 flex-col"
	>
		<Tabs.List class="grid w-full grid-cols-2">
			<Tabs.Trigger value="bitacora">
				<ScrollText class="mr-2 h-4 w-4" />
				{m['sidebar.audit_logs_tab_bitacora']()}
			</Tabs.Trigger>
			<Tabs.Trigger value="tasks">
				<ListTodo class="mr-2 h-4 w-4" />
				{m['sidebar.audit_logs_tab_tasks']()}
			</Tabs.Trigger>
		</Tabs.List>

		<Tabs.Content value="bitacora" class="mt-6 flex min-h-0 flex-1 flex-col overflow-hidden">
			{#if tabValue === 'bitacora'}
				<BitacoraTab />
			{/if}
		</Tabs.Content>
		<Tabs.Content value="tasks" class="mt-6 flex min-h-0 flex-1 flex-col overflow-hidden">
			{#if tabValue === 'tasks'}
				<TasksTab />
			{/if}
		</Tabs.Content>
	</Tabs.Root>
</div>
