<script lang="ts">
	import { onMount } from 'svelte';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Plus } from 'lucide-svelte';
	import DataTable from '$lib/components/dashboard/seal/data-table.svelte';
	import CreateEditDialog from '$lib/components/dashboard/seal/create-edit-dialog.svelte';
	import { createColumns } from '$lib/components/dashboard/seal/columns';
	import type { Seal } from '$lib/api/dashboard/a76/general_catalogs/seal';
	import { getSeals } from '$lib/api/dashboard/a76/general_catalogs/seal';
	import { companyStore } from '$lib/stores/company.svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaSellos } from '$lib/config/shortcuts/dashboard/general_catalogs/seal/list';

	let allItems = $state<Seal[]>([]);
	let loading = $state(false);
	let error = $state<string | null>(null);
	let currentPage = $state(1);
	const pageSize = 50;

	let dialogOpen = $state(false);

	// Atajos
	useShortcuts(
		'Lista Sellos',
		obtenerAtajosListaSellos({
			manejarNuevo: handleCreate,
			manejarActualizar: loadInitialData
		})
	);

	// Filters
	let sealFilter = $state('');

	let hasMore = $derived(allItems.length >= currentPage * pageSize);

	onMount(() => {
		// Sync access_token from cookies to localStorage
		const cookies = document.cookie.split(';');
		for (const cookie of cookies) {
			const [name, value] = cookie.trim().split('=');
			if (name === 'access_token') {
				localStorage.setItem('access_token', value);
				break;
			}
		}

		// Wait for companyStore to be initialized
		const checkAndLoad = () => {
			if (companyStore.activeCompany) {
				loadInitialData();
			} else {
				setTimeout(checkAndLoad, 100);
			}
		};

		checkAndLoad();

		// Listen for company changes
		const handleCompanyChange = () => {
			loadInitialData();
		};

		window.addEventListener('companyChanged', handleCompanyChange);

		return () => {
			window.removeEventListener('companyChanged', handleCompanyChange);
		};
	});

	async function loadInitialData() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			return;
		}

		allItems = [];
		currentPage = 1;
		await loadSeals(1);
	}

	async function loadSeals(page: number) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId || loading) {
			return;
		}

		loading = true;
		error = null;

		try {
			const filters: any = {
				page,
				page_size: pageSize
			};

			if (sealFilter) filters.seal = sealFilter;

			const response = await getSeals(companyId, filters);

			if (page === 1) {
				allItems = response.data.items;
			} else {
				allItems = [...allItems, ...response.data.items];
			}

			currentPage = page;
		} catch (err: any) {
			error = err.message || 'Error al cargar los sellos';
		} finally {
			loading = false;
		}
	}

	function loadMore() {
		if (!loading && hasMore) {
			loadSeals(currentPage + 1);
		}
	}

	function handleSearch() {
		loadInitialData();
	}

	function handleCreate() {
		dialogOpen = true;
	}

	function handleSuccess() {
		loadInitialData();
	}

	const columns = createColumns(handleSuccess);
</script>

<div class="flex flex-col gap-4 p-4">
	<div class="flex items-center justify-between">
		<div>
			<h1 class="text-2xl font-bold tracking-tight">Sellos</h1>
			<p class="text-muted-foreground">Gestiona los sellos de tu empresa</p>
		</div>
		<Button onclick={handleCreate}>
			<Plus class="mr-2 h-4 w-4" />
			Nuevo Sello
		</Button>
	</div>

	{#if error}
		<div class="rounded-md bg-destructive/15 p-4">
			<p class="text-sm text-destructive">{error}</p>
		</div>
	{/if}

	<div class="flex gap-4 items-end">
		<div class="grid w-full max-w-sm items-center gap-1.5">
			<Input
				placeholder="Filtrar por sello..."
				bind:value={sealFilter}
				oninput={handleSearch}
				disabled={loading}
			/>
		</div>
	</div>

	<div class="rounded-md border">
		<DataTable data={allItems} {columns} {loading} {hasMore} {loadMore} />
	</div>

	<CreateEditDialog bind:open={dialogOpen} onSuccess={handleSuccess} />
</div>
