<script lang="ts">
	import { onMount } from 'svelte';
	import { sectorsApi, type Sector } from '$lib/api/dashboard/reference_data/sectors';
	import { companyStore } from '$lib/stores/company.svelte';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { page } from '$app/stores';
	import { browser } from '$app/environment';
	import { RefreshCw, Plus, Pencil, Trash2 } from 'lucide-svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import type { PageData } from './$types';
	import { currentUser } from '$lib/auth';
	import { userHasSectorsRefAction } from '$lib/permissions/reference-data/sectors-ref-permissions';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
	import { createColumns } from '$lib/components/dashboard/reference_data/sectors/columns';
	import CreateEditDialog from '$lib/components/dashboard/reference_data/sectors/create-edit-dialog.svelte';
	import InfiniteDataTable from '$lib/components/dashboard/common/infinite-data-table.svelte';

	// Los datos iniciales vienen del servidor
	let { data }: { data: PageData } = $props();

	let allItems = $state<Sector[]>(data.items || []);
	let currentPage = $state(data.page || 1);
	let pageSize = $state(data.page_size || 50);
	let totalItems = $state(data.total || 0);
	let loading = $state(false);
	let hasMore = $derived(allItems.length < totalItems);
	let error = $state<string | null>(data.error || null);
	let status = $state<number>(data.status || 200);

	// Diálogos
	let createDialogOpen = $state(false);
	let editingItem = $state<Sector | null>(null);

	// Filtros
	let searchQuery = $state($page.url.searchParams.get('search') || '');
	let timeout: ReturnType<typeof setTimeout>;

	// Permisos
	const canView = $derived(userHasSectorsRefAction($currentUser, 'view'));
	const canCreate = $derived(false);
	const canEdit = $derived(false);
	const canDelete = $derived(false);

	const isError = $derived(!canView || status >= 400 || error);

	function getActiveCompanyId(): number | null {
		return companyStore.activeCompany?.id || null;
	}

	$effect(() => {
		if (data.items) {
			allItems = data.items;
			currentPage = data.page || 1;
			totalItems = data.total || 0;
			pageSize = data.page_size || pageSize;
		}
	});

	async function handleSearch() {
		if (!browser) return;
		clearTimeout(timeout);
		timeout = setTimeout(async () => {
			loading = true;
			error = null;
			try {
				const companyId = getActiveCompanyId();
				if (!companyId) return;

				const response = await sectorsApi.list(1, pageSize, companyId, searchQuery);
				if (response.data) {
					allItems = response.data.items;
					currentPage = 1;
					totalItems = response.data.total;
				}
			} catch (e) {
				console.error('Error aplicando filtros:', e);
			} finally {
				loading = false;
			}
			
			const url = new URL($page.url);
			if (searchQuery) url.searchParams.set('search', searchQuery);
			else url.searchParams.delete('search');
			history.replaceState(history.state, '', url);
		}, 500);
	}

	async function loadMore() {
		if (loading || !hasMore) return;
		loading = true;
		try {
			const companyId = getActiveCompanyId();
			if (!companyId) return;

			const response = await sectorsApi.list(currentPage + 1, pageSize, companyId, searchQuery);
			if (response.data?.items) {				
				allItems = [...allItems, ...response.data.items];
				currentPage++;
				totalItems = response.data.total;
			}
		} finally {
			loading = false;
		}
	}

	function reloadData() {
		if (browser) window.location.reload();
	}

	function handleSuccess() {
		createDialogOpen = false;
		editingItem = null;
		reloadData();
	}

	useShortcuts('Sectores', [
		{ key: 'Alt+Shift+R', description: 'Actualizar Lista', action: reloadData },
		{
			key: 'Ctrl+S',
			description: 'Guardar',
			action: () => {
				if (!createDialogOpen) return;
				document.dispatchEvent(new CustomEvent('save-form'));
			}
		}
	]);

	const columns = $derived(createColumns(handleSuccess, { canEdit, canDelete }));
</script>

<div class="flex flex-col gap-6 p-6 h-[calc(100svh-4rem)] group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)] overflow-hidden">
	<div class="flex-none flex items-center justify-between">
		<div class="space-y-1">
			<h1 class="text-2xl font-bold tracking-tight">Sectores</h1>
			<p class="text-muted-foreground">Gestiona los sectores económicos del sistema</p>
		</div>
		<div class="flex items-center gap-3">
			<Button variant="outline" size="sm" class="h-9" onclick={reloadData}>
				<RefreshCw class="mr-2 h-4 w-4" /> Actualizar
			</Button>
			{#if canCreate}
				<Button size="sm" class="h-9" onclick={() => { editingItem = null; createDialogOpen = true; }}>
					<Plus class="mr-2 h-4 w-4" /> Nuevo Sector
				</Button>
			{/if}
		</div>
	</div>

	{#if isError}
		<ErrorState 
			status={!canView ? 403 : status} 
			error={!canView ? 'Permission denied: ref_sectors.view' : error || ''} 
			onRetry={reloadData} 
		/>
	{:else}
		<Card.Root class="border bg-background flex min-h-0 flex-1 flex-col overflow-hidden">
			<Card.Header>
				<div class="flex flex-wrap items-center justify-between gap-3">
					<Card.Title>Listado de Sectores</Card.Title>
					<div class="flex flex-wrap items-center gap-2">
						<Input placeholder="Buscar" bind:value={searchQuery} oninput={handleSearch} class="h-9 w-44 bg-card lg:w-64" />
					</div>
				</div>
			</Card.Header>
			<Card.Content class="min-h-0 p-0 flex-1 overflow-hidden flex flex-col">
				<div class="rounded-md border bg-background overflow-hidden flex-1 h-full">
					<InfiniteDataTable data={allItems} {columns} {loading} {hasMore} {loadMore} />
				</div>
			</Card.Content>
		</Card.Root>

		<div class="flex-none text-sm text-muted-foreground">Mostrando {allItems.length} de {totalItems} registros</div>
	{/if}
</div>

<CreateEditDialog bind:open={createDialogOpen} item={editingItem} onSuccess={handleSuccess} />
