<script lang="ts">
	import { userHasPackagesAction } from '$lib/permissions/catalogs/packages-permissions';

import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { browser } from '$app/environment';
import { createColumns } from '$lib/components/dashboard/packages/columns';
import CreateEditDialog from '$lib/components/dashboard/packages/create-edit-dialog.svelte';
import InfiniteDataTable from '$lib/components/dashboard/common/infinite-data-table.svelte';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import { Input } from '$lib/components/ui/input';
import { Pencil, Plus, Trash2, RefreshCw } from 'lucide-svelte';
import { useShortcuts } from '$lib/hooks/use-shortcuts';
import { obtenerAtajosListaBultos } from '$lib/config/shortcuts/dashboard/general_catalogs/packages/list';
import { packagesApi, type Package } from '$lib/api/dashboard/a76/general_catalogs/packages';
import { companyStore } from '$lib/stores/company.svelte';
import { currentUser } from '$lib/auth';
import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

let { data } = $props();

let createDialogOpen = $state(false);
let editingItem = $state<Package | null>(null);
let error = $state<string | null>(data.error || null);
let status = $state<number>(data.status || 200);

// Permisos
const canView = $derived(userHasPackagesAction($currentUser, 'view'));
const canCreate = $derived(userHasPackagesAction($currentUser, 'create'));
const canEdit = $derived(userHasPackagesAction($currentUser, 'edit'));
const canDelete = $derived(userHasPackagesAction($currentUser, 'delete'));

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

// Atajos
useShortcuts(
'Lista Embalajes',
obtenerAtajosListaBultos({
manejarNuevo: () => {
if (!canCreate) return;
editingItem = null;
createDialogOpen = true;
},
manejarActualizar: () => reloadData()
})
);

// Filtros
let searchCode = $state($page.url.searchParams.get('code') || '');
let searchDesc = $state($page.url.searchParams.get('description') || '');
let timeout: ReturnType<typeof setTimeout>;

let allItems = $state<Package[]>(data.packages?.items || data.packages || []);
let currentPage = $state(data.packages?.page || 1);
let pageSize = $state(data.packages?.page_size || 50);
let totalItems = $state(data.packages?.total || 0);
let loading = $state(false);
let hasMore = $derived(allItems.length < totalItems);
let selectedIds = $state<(string | number)[]>([]);
const selectedItem = $derived(
selectedIds.length === 1
? allItems.find((item) => String(item.id) === String(selectedIds[0])) ?? null
: null
);

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

async function handleSearch() {
if (!browser) return;
clearTimeout(timeout);
timeout = setTimeout(async () => {
if (!companyStore.activeCompany) return;
loading = true;
error = null;
try {
const response = await packagesApi.list(companyStore.activeCompany.id, {
code: searchCode || undefined,
description: searchDesc || undefined,
page: '1',
page_size: pageSize.toString()
});
if (response.data) {
allItems = response.data.items;
currentPage = 1;
totalItems = response.data.total;
}
} catch (err) {
error = 'Error aplicando filtros';
} finally {
loading = false;
}

const url = new URL($page.url);
if (searchCode) url.searchParams.set('code', searchCode);
else url.searchParams.delete('code');
if (searchDesc) url.searchParams.set('description', searchDesc);
else url.searchParams.delete('description');
history.replaceState(history.state, '', url);
}, 500);
}

async function loadMore() {
if (loading || !hasMore || !companyStore.activeCompany) return;
loading = true;
try {
const response = await packagesApi.list(companyStore.activeCompany.id, {
code: searchCode || undefined,
description: searchDesc || undefined,
page: (currentPage + 1).toString(),
page_size: pageSize.toString()
});
if (response.data?.items) {
allItems = [...allItems, ...response.data.items];
currentPage += 1;
totalItems = response.data.total;
}
} finally {
loading = false;
}
}

async function reloadData() {
if (!companyStore.activeCompany) return;
loading = true;
error = null;
try {
const response = await packagesApi.list(companyStore.activeCompany.id, {
code: searchCode || undefined,
description: searchDesc || undefined,
page: '1',
page_size: pageSize.toString()
});
if (response.data) {
allItems = response.data.items;
currentPage = 1;
totalItems = response.data.total;
}
} finally {
loading = false;
}
}

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

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

<div class="flex h-[calc(100svh-4rem)] flex-col gap-6 overflow-hidden p-6 group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)]">
<div class="flex flex-none items-center justify-between">
<div>
<h1 class="text-2xl font-bold tracking-tight">Embalajes</h1>
<p class="text-muted-foreground">Catálogo de Embalajes 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 !isError && canCreate}
<Button class="h-9" onclick={() => { editingItem = null; createDialogOpen = true; }}>
<Plus class="mr-2 h-4 w-4" /> Nuevo Registro
</Button>
{/if}
</div>
</div>

{#if isError}
<ErrorState
status={!canView ? 403 : status}
error={!canView ? 'Permission denied: cat_packages.view' : error || ''}
onRetry={reloadData}
/>
{:else}
<Card.Root class="flex min-h-0 flex-1 flex-col overflow-hidden border bg-background">
<Card.Header>
<div class="flex flex-wrap items-center justify-between gap-3">
<Card.Title>Listado de Embalajes</Card.Title>
<div class="flex flex-wrap items-center gap-2">
<Input placeholder="Código" bind:value={searchCode} oninput={handleSearch} class="h-9 w-36 bg-card lg:w-44" />
<Input placeholder="Descripción" bind:value={searchDesc} oninput={handleSearch} class="h-9 w-44 bg-card lg:w-64" />
</div>
</div>
</Card.Header>
<Card.Content class="min-h-0 flex-1 overflow-hidden p-0">
<div class="h-full overflow-hidden rounded-md border bg-background">
<InfiniteDataTable 
data={allItems} {columns} {loading} {hasMore} {loadMore} 
{selectedIds} onSelectedIdsChange={(ids) => (selectedIds = ids)}
onRowClick={(row) => selectedIds = selectedIds.includes(row.id) ? [] : [row.id]}
onRowDoubleClick={(row) => { if(canEdit) { editingItem = row; createDialogOpen = true; } }}
/>
</div>
</Card.Content>
</Card.Root>

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


<div class="fixed right-0 bottom-0 left-0 z-50 ml-[calc(var(--sidebar-width))] border-t bg-background/95 shadow-lg backdrop-blur group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] supports-[backdrop-filter]:bg-background/80">
<div class="mx-auto max-w-[1400px] px-4 py-4">
<div class="flex justify-end gap-2">
{#if canEdit}
<Button variant="outline" size="sm" onclick={() => { editingItem = selectedItem; createDialogOpen = true; }} disabled={!selectedItem}>
<Pencil size={16} class="mr-2" /> Editar
</Button>
{/if}
{#if canDelete}
<Button variant="outline" size="sm" onclick={async () => {
if(!selectedItem || !companyStore.activeCompany) return;
if(confirm('¿Eliminar este registro?')) {
await packagesApi.delete(selectedItem.id, companyStore.activeCompany.id);
selectedIds = [];
reloadData();
}
}} disabled={!selectedItem} class="text-destructive hover:bg-destructive/10">
<Trash2 size={16} class="mr-2" /> Eliminar
</Button>
{/if}
</div>
</div>
</div>
{/if}

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