<script lang="ts">
	import { userHasClassificationConceptsAction } from '$lib/permissions/catalogs/classification-concepts-permissions';

import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { browser } from '$app/environment';
import { createColumns } from '$lib/components/dashboard/general_catalogs/classification_concepts/columns';
import CreateEditDialog from '$lib/components/dashboard/general_catalogs/classification_concepts/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 { obtenerAtajosListaClasificacion } from '$lib/config/shortcuts/dashboard/general_catalogs/classification/list';
import { classificationApi, type ClassificationConcept } from '$lib/api/dashboard/a76/general_catalogs/classification-concepts';
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 dialogOpen = $state(false);
let editingItem = $state<ClassificationConcept | null>(null);
let error = $state<string | null>(data.error || null);
let status = $state<number>(data.status || 200);

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

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

// Atajos
useShortcuts(
'Lista Clasificaciones de Conceptos',
obtenerAtajosListaClasificacion({
manejarNuevo: () => {
if (!canCreate) return;
editingItem = null;
dialogOpen = true;
},
manejarActualizar: () => reloadData()
})
);

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

let allItems = $state<ClassificationConcept[]>(data.classifications?.items || []);
let currentPage = $state(data.classifications?.page || 1);
let pageSize = $state(data.classifications?.page_size || 50);
let totalItems = $state(data.classifications?.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.classifications) {
allItems = data.classifications.items || [];
currentPage = data.classifications.page || 1;
totalItems = data.classifications.total || 0;
pageSize = data.classifications.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 classificationApi.list(companyStore.activeCompany.id, {
classification: searchKey || undefined,
description: searchDesc || undefined,
page: '1',
page_size: pageSize.toString()
});
if (response.data?.items) {
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 (searchKey) url.searchParams.set('classification', searchKey);
else url.searchParams.delete('classification');
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 classificationApi.list(companyStore.activeCompany.id, {
classification: searchKey || undefined,
description: searchDesc || undefined,
page: (currentPage + 1).toString(),
page_size: pageSize.toString()
});
if (response.data?.items) {
allItems = [...allItems, ...response.data.items];
currentPage = response.data.page || (currentPage + 1);
totalItems = response.data.total;
}
} catch (err) {
error = 'Error cargando mas datos';
} finally {
loading = false;
}
}

async function reloadData() {
if (!companyStore.activeCompany) return;
loading = true;
error = null;
try {
const response = await classificationApi.list(companyStore.activeCompany.id, {
classification: searchKey || undefined,
description: searchDesc || undefined,
page: '1',
page_size: pageSize.toString()
});
if (response.data?.items) {
allItems = response.data.items;
currentPage = 1;
totalItems = response.data.total;
}
} catch (err) {
error = 'Error al recargar datos';
} finally {
loading = false;
}
}

function handleSuccess() {
dialogOpen = 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">Clasificaciones de Conceptos</h1>
<p class="text-muted-foreground">Catálogo de Clasificaciones de Conceptos</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; dialogOpen = 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_classification.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</Card.Title>
<div class="flex flex-wrap items-center gap-2">
<Input placeholder="Clasificación" bind:value={searchKey} oninput={handleSearch} class="h-9 w-40 bg-card lg:w-52" />
<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; dialogOpen = 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; dialogOpen = 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 classificationApi.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={dialogOpen} item={editingItem} onSuccess={handleSuccess} />
</div>