<script lang="ts">
	import { userHasCompanyCatalogAction } from '$lib/permissions/catalogs/company-catalog-permissions';

	import { page } from '$app/stores';
	import InfiniteDataTable from '$lib/components/dashboard/common/infinite-data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/general_catalogs/company/columns';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';

	import { Input } from '$lib/components/ui/input';
	import { Plus, RefreshCw } from 'lucide-svelte';
	import { goto } from '$app/navigation';
	import { browser } from '$app/environment';
	import * as m from '$lib/paraglide/messages.js';

	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaEmpresa } from '$lib/config/shortcuts/dashboard/general_catalogs/company_information/list';
	import { getCompanies } from '$lib/api/dashboard/a76/general_catalogs/company';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
	import { currentUser } from '$lib/auth';
	let { data } = $props();

	// Atajos
	useShortcuts(
		'Lista Empresas',
		obtenerAtajosListaEmpresa({
			manejarNuevo: () => {
				if (!canCreate) return;
				goto('/dashboard/general_catalogs/company_information/edit');
			},
			manejarActualizar: () => goto($page.url, { invalidateAll: true })
		})
	);
	let dialogOpen = $state(false);
	let error = $state<string | null>(data.error || null);
	let status = $state<number>(data.status || 200);

	// Determinar permisos
	const canView = $derived(userHasCompanyCatalogAction($currentUser, 'view'));
	const canCreate = $derived(userHasCompanyCatalogAction($currentUser, 'create'));
	const canEdit = $derived(userHasCompanyCatalogAction($currentUser, 'edit'));
	const canDelete = $derived(userHasCompanyCatalogAction($currentUser, 'delete'));

	// Filtros
	let searchName = $state($page.url.searchParams.get('name') || '');
	let searchRfc = $state($page.url.searchParams.get('rfc') || '');
	let timeout: ReturnType<typeof setTimeout>;

	let allItems = $state(data.companies?.items || []);
	let currentPage = $state(data.companies?.page || 1);
	let pageSize = $state(data.companies?.page_size || 50);
	let totalItems = $state(data.companies?.total || 0);
	let loading = $state(false);
	let hasMore = $derived(allItems.length < totalItems);

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

	async function handleSearch() {
		if (!browser) return;
		clearTimeout(timeout);
		timeout = setTimeout(async () => {
			loading = true;
			error = null;
			try {
				const filters: Record<string, string> = {};
				if (searchName) filters.name = searchName;
				if (searchRfc) filters.rfc = searchRfc;

				const response = await getCompanies(1, pageSize, filters);
				if (response.data) {
					allItems = response.data.items;
					currentPage = 1;
					totalItems = response.data.total;
				}
			} catch (err) {
				error = 'Error aplicando filtros';
				console.error('Error applying filters:', err);
			} finally {
				loading = false;
			}

			const url = new URL($page.url);
			if (searchName) url.searchParams.set('name', searchName);
			else url.searchParams.delete('name');

			if (searchRfc) url.searchParams.set('rfc', searchRfc);
			else url.searchParams.delete('rfc');

			history.replaceState(history.state, '', url);
		}, 500);
	}

	async function loadMore() {
		if (loading || !hasMore) return;
		loading = true;
		error = null;
		try {
			const filters: Record<string, string> = {};
			if (searchName) filters.name = searchName;
			if (searchRfc) filters.rfc = searchRfc;

			const response = await getCompanies(currentPage + 1, pageSize, filters);
			if (response.data?.items) {
				allItems = [...allItems, ...response.data.items];
				currentPage += 1;
				totalItems = response.data.total;
			}
		} catch (err) {
			error = 'Error cargando mas datos';
			console.error('Error loading more companies:', err);
		} finally {
			loading = false;
		}
	}

	async function reloadData() {
		loading = true;
		error = null;
		try {
			const filters: Record<string, string> = {};
			if (searchName) filters.name = searchName;
			if (searchRfc) filters.rfc = searchRfc;

			const response = await getCompanies(1, pageSize, filters);
			if (response.data) {
				allItems = response.data.items;
				currentPage = 1;
				totalItems = response.data.total;
			}
		} catch (err) {
			error = 'Error al recargar datos';
			console.error('Error reloading companies:', err);
		} finally {
			loading = false;
		}
	}

	function handleSuccess() {
		reloadData();
	}
</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 items-center justify-between">
		<div>
			<h1 class="text-2xl font-bold tracking-tight">Información de Empresas</h1>
			<p class="text-muted-foreground">Gestión de información de empresas</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 class="h-9" href="/dashboard/general_catalogs/company_information/edit">
					<Plus class="mr-2 h-4 w-4" />
					Nueva Empresa
				</Button>
			{/if}
		</div>
	</div>

	{#if error || !canView}
		<ErrorState 
			status={!canView ? 403 : status} 
			error={!canView ? 'Permission denied: cat_company.view' : (error || '')} 
			onRetry={reloadData}
		/>
	{:else}
		<Card.Root class="border bg-background flex flex-col">
		<Card.Header>
			<div class="flex flex-wrap items-center justify-between gap-3">
				<Card.Title>Listado de Empresas</Card.Title>
				<div class="flex flex-wrap items-center gap-2">
					<Input
						placeholder="Nombre"
						bind:value={searchName}
						oninput={handleSearch}
						class="h-9 w-40 bg-card lg:w-56"
					/>
					<Input
						placeholder="RFC"
						bind:value={searchRfc}
						oninput={handleSearch}
						class="h-9 w-36 bg-card lg:w-44"
					/>
				</div>
			</div>
		</Card.Header>
		<Card.Content class="p-0">
			<div class="rounded-md border bg-background overflow-hidden">
				<InfiniteDataTable
					data={allItems}
					columns={createColumns(handleSuccess, { canEdit, canDelete })}
					{loading}
					{hasMore}
					{loadMore}
					onRowDoubleClick={(row) => {
						if (canEdit) {
							goto(`/dashboard/general_catalogs/company_information/edit/${row.id}`);
						}
					}}
				/>
			</div>
		</Card.Content>
	</Card.Root>
	{/if}

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