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

	import { createColumns } from '$lib/components/dashboard/locations/columns';
	import CreateDialog from '$lib/components/dashboard/general_catalogs/locations/create-edit-dialog.svelte';
	import DataTable from '$lib/components/dashboard/locations/data-table.svelte';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Plus } from 'lucide-svelte';
	import {
		getLocations,
		type Location,
		type LocationSystem
	} from '$lib/api/dashboard/a76/general_catalogs/locations';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
	import { currentUser } from '$lib/auth';
	let {
		companyId,
		system: initialSystem = undefined,
		showSystemFilter = true,
		compact = false
	}: {
		companyId: number;
		/** Filtro por sistema cuando está embebido (ej. solo fixed_asset o solo inventory). */
		system?: LocationSystem;
		/** Mostrar selector de sistema (FA / Inventario). Por defecto true. */
		showSystemFilter?: boolean;
		/** Vista compacta sin título ni descripción. */
		compact?: boolean;
	} = $props();

	let items = $state<Location[]>([]);
	let total = $state(0);
	let page = $state(1);
	let pageSize = $state(50);
	let pages = $state(0);
	let loading = $state(true);
	let status = $state(200);
	let dialogOpen = $state(false);
	let searchClave = $state('');
	let searchLocalizacion = $state('');
	let filterSystem = $state<LocationSystem | ''>(initialSystem ?? '');
	let timeout: ReturnType<typeof setTimeout>;
	const canView = $derived(userHasLocationsCatalogAction($currentUser, 'view'));
	const canCreate = $derived(userHasLocationsCatalogAction($currentUser, 'create'));
	const canEdit = $derived(userHasLocationsCatalogAction($currentUser, 'edit'));
	const canDelete = $derived(userHasLocationsCatalogAction($currentUser, 'delete'));

	async function load() {
		if (!companyId) return;
		if (!canView) {
			loading = false;
			items = [];
			total = 0;
			pages = 0;
			status = 403;
			return;
		}
		loading = true;
		try {
			const filters: Record<string, string | number> = {
				page,
				page_size: pageSize
			};
			if (searchClave) filters.clave_localizacion = searchClave;
			if (searchLocalizacion) filters.localizacion = searchLocalizacion;
			if (filterSystem) filters.system = filterSystem;
			const res = await getLocations(companyId, filters);
			items = res.items ?? [];
			total = res.total ?? 0;
			status = 200;
			page = res.page ?? 1;
			pageSize = res.page_size ?? 50;
			pages = pageSize > 0 ? Math.ceil(total / pageSize) : 0;
		} catch (e) {
			console.error('Error loading locations:', e);
			items = [];
			total = 0;
			pages = 0;
			status = 500;
		} finally {
			loading = false;
		}
	}

	function handleSuccess() {
		load();
	}

	function handleSearch() {
		clearTimeout(timeout);
		timeout = setTimeout(() => {
			page = 1;
			load();
		}, 400);
	}

	$effect(() => {
		void companyId;
		void page;
		void canView;
		load();
	});
</script>

<div class="flex flex-col gap-4">
	{#if !canView}
		<ErrorState status={403} error="Permission denied: cat_locations.view" />
	{:else}
	{#if !compact}
		<div class="flex items-center justify-between">
			<div>
				<h2 class="text-lg font-semibold tracking-tight">Ubicaciones</h2>
				<p class="text-sm text-muted-foreground">
					Clave y localización por sistema (FA / Inventario)
				</p>
			</div>
			<Button onclick={() => (dialogOpen = true)} size="sm" disabled={!canCreate}>
				<Plus class="mr-2 h-4 w-4" />
				Nueva
			</Button>
		</div>
	{:else}
		<div class="flex items-center justify-end">
			<Button onclick={() => (dialogOpen = true)} size="sm" variant="outline" disabled={!canCreate}>
				<Plus class="mr-2 h-4 w-4" />
				Nueva ubicación
			</Button>
		</div>
	{/if}

	<div class="flex gap-4 items-end flex-wrap">
		<div class="grid w-full max-w-[200px] items-center gap-1.5">
			<Input
				placeholder="Clave..."
				bind:value={searchClave}
				oninput={handleSearch}
			/>
		</div>
		<div class="grid w-full max-w-[200px] items-center gap-1.5">
			<Input
				placeholder="Localización..."
				bind:value={searchLocalizacion}
				oninput={handleSearch}
			/>
		</div>
		{#if showSystemFilter}
			<div class="grid w-full max-w-[180px] items-center gap-1.5">
				<select
					bind:value={filterSystem}
					onchange={handleSearch}
					class="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm"
				>
					<option value="">Todos</option>
					<option value="fixed_asset">Activo fijo (FA)</option>
					<option value="inventory">Inventario</option>
				</select>
			</div>
		{/if}
	</div>

	<div class="rounded-md border">
		{#if loading}
			<div class="flex items-center justify-center py-12 text-muted-foreground">
				Cargando...
			</div>
		{:else}
			<DataTable
				data={items}
				columns={createColumns(handleSuccess, { canEdit, canDelete })}
				pageCount={pages}
				totalItems={total}
			/>
		{/if}
	</div>

	<CreateDialog bind:open={dialogOpen} onSuccess={handleSuccess} canMutate={canCreate} />
	{/if}
</div>
