<script lang="ts">
	import { userHasUnitConversionsAction } from '$lib/permissions/catalogs/unit-conversions-permissions';

import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { browser } from '$app/environment';
import { createColumns } from '$lib/components/dashboard/general_catalogs/unit_conversions/columns';
import CreateEditDialog from '$lib/components/dashboard/general_catalogs/unit_conversions/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 { obtenerAtajosListaConversiones } from '$lib/config/shortcuts/dashboard/general_catalogs/unit_conversions/list';
import { unitConversionsApi, type UnitConversion } from '$lib/api/dashboard/a76/general_catalogs/unit-conversions';
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<UnitConversion | null>(null);
let error = $state<string | null>(data.error || null);
let status = $state<number>(data.status || 200);

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

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

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

// Filtros
let searchFrom = $state($page.url.searchParams.get('from_unit_code') || '');
let searchTo = $state($page.url.searchParams.get('to_unit_code') || '');
let timeout: ReturnType<typeof setTimeout>;

let allItems = $state<UnitConversion[]>(data.conversions?.items || []);
let currentPage = $state(data.conversions?.page || 1);
let pageSize = $state(data.conversions?.page_size || 50);
let totalItems = $state(data.conversions?.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.conversions) {
allItems = data.conversions.items || [];
currentPage = data.conversions.page || 1;
totalItems = data.conversions.total || 0;
pageSize = data.conversions.page_size || pageSize;
}
});

async function handleSearch() {
if (!browser) return;
clearTimeout(timeout);
timeout = setTimeout(async () => {
if (!companyStore.activeCompany) return;
loading = true;
error = null;
try {
const filters: Record<string, string> = {};
if (searchFrom) filters.from_unit_code = searchFrom;
if (searchTo) filters.to_unit_code = searchTo;

const response = await unitConversionsApi.list(1, pageSize, companyStore.activeCompany.id, filters);
const payload = response;
if (payload?.items) {
allItems = payload.items;
currentPage = payload.page || 1;
totalItems = payload.total;
}
} catch (err) {
error = 'Error aplicando filtros';
console.error('Error applying filters:', err);
} finally {
loading = false;
}

const url = new URL($page.url);
if (searchFrom) url.searchParams.set('from_unit_code', searchFrom);
else url.searchParams.delete('from_unit_code');
if (searchTo) url.searchParams.set('to_unit_code', searchTo);
else url.searchParams.delete('to_unit_code');
history.replaceState(history.state, '', url);
}, 500);
}

async function loadMore() {
if (loading || !hasMore || !companyStore.activeCompany) return;
loading = true;
error = null;
try {
const filters: Record<string, string> = {};
if (searchFrom) filters.from_unit_code = searchFrom;
if (searchTo) filters.to_unit_code = searchTo;

const response = await unitConversionsApi.list(currentPage + 1, pageSize, companyStore.activeCompany.id, filters);
const payload = response;
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 unitConversionsApi.list(1, pageSize, companyStore.activeCompany.id, {
from_unit_code: searchFrom || undefined,
to_unit_code: searchTo || undefined
});
const payload = response;
if (payload?.items) {
allItems = payload.items;
currentPage = payload.page || 1;
totalItems = payload.total;
}
} catch (err) {
error = 'Error al recargar datos';
} finally {
loading = false;
}
}

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

    function handleNew() {
        if (!canCreate) return;
        editingItem = null;
        createDialogOpen = true;
    }

    function handleEdit() {
        if (!selectedItem || !canEdit) return;
        editingItem = selectedItem;
        createDialogOpen = true;
    }



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

    function handleRowDoubleClick(row: UnitConversion) {
        if (canEdit) {
            editingItem = row;
            createDialogOpen = true;
        }
    }

    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">Conversiones de Unidades</h1>
<p class="text-muted-foreground">Gestión del catálogo de conversiones de unidades entre sistemas</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" /> Nueva Conversión
</Button>
{/if}
</div>
</div>

{#if isError}
<ErrorState
status={!canView ? 403 : status}
error={!canView ? 'Permission denied: cat_unit_conversions.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 Conversiones</Card.Title>
<div class="flex flex-wrap items-center gap-2">
<Input placeholder="Desde" bind:value={searchFrom} oninput={handleSearch} class="h-9 w-36 bg-card lg:w-44" />
<Input placeholder="Hacia" bind:value={searchTo} oninput={handleSearch} class="h-9 w-36 bg-card lg:w-44" />
</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}

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