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

import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { browser } from '$app/environment';
import { createColumns } from '$lib/components/dashboard/general_catalogs/doda/columns';
import DodaFormModal from '$lib/components/dashboard/general_catalogs/doda/doda-form-modal.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 { obtenerAtajosListaDoda } from '$lib/config/shortcuts/dashboard/general_catalogs/doda/list';
import { dodaApi, type Doda } from '$lib/api/dashboard/a76/general_catalogs/doda';
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<Doda | null>(null);
let error = $state<string | null>(data.error || null);
let status = $state<number>(data.status || 200);

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

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

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

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

let allItems = $state<Doda[]>(data.dodas?.items || []);
let currentPage = $state(data.dodas?.page || 1);
let pageSize = $state(data.dodas?.page_size || 50);
let totalItems = $state(data.dodas?.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.dodas) {
        allItems = data.dodas.items || [];
        currentPage = data.dodas.page || 1;
        totalItems = data.dodas.total || 0;
        pageSize = data.dodas.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 dodaApi.list(1, pageSize, companyStore.activeCompany.id, {
            folio: searchKey || undefined,
            description: searchDesc || undefined
        });
const payload = response.data;
if (payload?.items) {
allItems = payload.items;
currentPage = payload.page || 1;
totalItems = payload.total;
}
} catch (err) {
error = 'Error aplicando filtros';
} finally {
loading = false;
}

const url = new URL($page.url);
if (searchKey) url.searchParams.set('folio', searchKey);
else url.searchParams.delete('folio');
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 dodaApi.list(currentPage + 1, pageSize, companyStore.activeCompany.id, {
            folio: searchKey || undefined,
            description: searchDesc || undefined
        });
const payload = response.data;
if (payload?.items) {
allItems = [...allItems, ...payload.items];
currentPage = payload.page || (currentPage + 1);
totalItems = payload.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 dodaApi.list(1, pageSize, companyStore.activeCompany.id, {
            folio: searchKey || undefined,
            description: searchDesc || undefined
        });
const payload = response.data;
if (payload?.items) {
allItems = payload.items;
currentPage = payload.page || 1;
totalItems = payload.total;
}
} catch (err) {
error = 'Error al recargar datos';
} finally {
loading = false;
}
}

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

    function handleNew() {
        if (!canCreate) return;
        const url = new URL($page.url);
        url.searchParams.set('doda_id', 'new');
        goto(url.toString(), { replaceState: true });
    }

    function handleEdit() {
        if (!selectedItem || !canEdit) return;
        const url = new URL($page.url);
        url.searchParams.set('doda_id', selectedItem.id.toString());
        goto(url.toString(), { replaceState: true });
    }

    async function handleDelete() {
        if (!selectedItem || !canDelete || !companyStore.activeCompany) return;
        if (confirm('¿Eliminar este registro?')) {
            try {
                await dodaApi.delete(selectedItem.id, companyStore.activeCompany.id);
                selectedIds = [];
                reloadData();
            } catch (err) {
                error = 'Error al eliminar';
            }
        }
    }

    function handleRowClick(row: Doda) {
        selectedIds = selectedIds.includes(row.id) ? [] : [row.id];
    }

    function handleRowDoubleClick(row: Doda) {
        if (canEdit) {
            const url = new URL($page.url);
            url.searchParams.set('doda_id', row.id.toString());
            goto(url.toString(), { replaceState: true });
        }
    }

    const columns = $derived(createColumns('es', 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">DODA</h1>
<p class="text-muted-foreground">Catálogo de DODA</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={handleNew}>
<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_doda.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="Folio" 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={handleRowClick}
onRowDoubleClick={handleRowDoubleClick}
/>
</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={handleEdit} disabled={!selectedItem}>
<Pencil size={16} class="mr-2" /> Editar
</Button>
{/if}
{#if canDelete}
<Button variant="outline" size="sm" onclick={handleDelete} disabled={!selectedItem} class="text-destructive hover:bg-destructive/10">
<Trash2 size={16} class="mr-2" /> Eliminar
</Button>
{/if}
</div>
</div>
</div>
{/if}

{#if $page.url.searchParams.get('doda_id')}
<DodaFormModal 
dodaIdParam={$page.url.searchParams.get('doda_id')!} 
onClose={() => {
const url = new URL($page.url);
url.searchParams.delete('doda_id');
goto(url.toString(), { replaceState: true });
reloadData();
}}
onCreatedNavigateTo={(newId) => {
const url = new URL($page.url);
url.searchParams.set('doda_id', String(newId));
goto(url.toString(), { replaceState: true });
}}
/>
{/if}
</div>