<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Plus, RefreshCw, Package, Folder, CheckSquare } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { partsApi, type Part } from '$lib/api/dashboard/a76/parts';
	import { companyStore } from '$lib/stores/company.svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { goto } from '$app/navigation';
	import DataTable from '$lib/components/dashboard/goods/parts/data-table.svelte';
	import { createColumns } from '$lib/components/dashboard/goods/parts/columns';
	import { obtenerAtajosListaMercancias } from '$lib/config/shortcuts/dashboard/goods/list';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
	import {
		canCreateGoodsParts,
		canDeleteGoodsParts,
		canEditGoodsParts,
		canViewGoodsParts
	} from '$lib/permissions/goods-parts-permissions';
	import { formatMexTariffDigitsForDisplay } from '$lib/utils/mexican-tariff-fraction';

	let parts = $state<Part[]>([]);
	let isLoading = $state(false);
	let searchPartNumber = $state('');
	let searchDescription = $state('');
	let searchClass = $state('');
	let sorting = $state<import('@tanstack/table-core').SortingState>([
		{ id: 'updated_at', desc: true }
	]);
	let rowSelection = $state<import('@tanstack/table-core').RowSelectionState>({});

	let error = $state<string | null>(null);
	let status = $state<number>(200);
	let showDeleteDialog = $state(false);

	// Permisos
	const canView = $derived(canViewGoodsParts($currentUser));
	const canCreate = $derived(canCreateGoodsParts($currentUser));
	const canEdit = $derived(canEditGoodsParts($currentUser));
	const canDelete = $derived(canDeleteGoodsParts($currentUser));

	const columns = $derived(
		createColumns(() => loadParts(), {
			canEdit,
			canDelete
		})
	);

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

	// Filtros locales
	const filteredParts = $derived(
		parts.filter((p) => {
			const matchesPartNumber =
				!searchPartNumber || p.part_number.toLowerCase().includes(searchPartNumber.toLowerCase());
			const matchesDescription =
				!searchDescription ||
				(p.description_spanish?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false) ||
				(p.description_english?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false);
			const matchesClass =
				!searchClass || (p.part_class?.toLowerCase().includes(searchClass.toLowerCase()) ?? false);
			return matchesPartNumber && matchesDescription && matchesClass;
		})
	);

	// MULTI-SELECT LÓGICA
	const selectedPartIds = $derived(Object.keys(rowSelection).filter((id) => rowSelection[id]));
	const selectedParts = $derived(
		filteredParts.filter((p) => selectedPartIds.includes(p.id.toString()))
	);
	const activePart = $derived(selectedParts.length === 1 ? selectedParts[0] : null);

	$effect(() => {
		const companyId = companyStore.activeCompany?.id;
		if (companyId && sorting) {
			loadData();
		}
	});

	useShortcuts(
		'Goods List',
		obtenerAtajosListaMercancias({
			crear: () => {
				if (!canCreate) {
					toast.error('No tienes permiso para crear partes');
					return;
				}
				goto('/dashboard/goods/parts/edit/new');
			},
			recargar: loadData,
			editar: () => {
				if (!canEdit) {
					toast.error('No tienes permiso para editar partes');
					return;
				}
				if (activePart?.id) goto(`/dashboard/goods/parts/edit/${activePart.id}`);
				else toast.info('Seleccione una sola parte para editar');
			},
			eliminar: () => {
				if (!canDelete) {
					toast.error('No tienes permiso para eliminar partes');
					return;
				}
				if (selectedParts.length > 0) handleDelete();
				else toast.info('Seleccione al menos una parte para eliminar');
			}
		})
	);

	async function loadData() {
		if (!canView) return;
		await loadParts();
	}

	async function loadParts() {
		if (!canView) return;
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		isLoading = true;
		try {
			const response = await partsApi.list({
				company_id: companyId,
				page: 1,
				page_size: 1000,
				sort_by: sorting.length > 0 ? sorting[0].id : undefined,
				sort_order: sorting.length > 0 ? (sorting[0].desc ? 'desc' : 'asc') : undefined
			});

			if (response.data) {
				parts = response.data.items || [];
			}
		} catch (error) {
			console.error('Error cargando partes:', error);
			toast.error('Error al cargar las partes');
		} finally {
			isLoading = false;
		}
	}

	async function handleRefresh() {
		if (!canView) return;
		await loadData();
		toast.success('Partes actualizadas');
	}

	function handleDelete() {
		if (!canDelete) return;
		if (selectedParts.length === 0) {
			toast.error('Selecciona al menos una parte para borrar');
			return;
		}
		showDeleteDialog = true;
	}

	async function confirmDelete() {
		if (selectedParts.length === 0) return;

		isLoading = true;
		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) return;

			// Borrado en lote usando Promise.all
			await Promise.all(selectedParts.map((part) => partsApi.delete(part.id, companyId)));

			toast.success(`${selectedParts.length} parte(s) eliminada(s) exitosamente`);
			rowSelection = {}; // Limpiamos la selección
			await loadData();
			showDeleteDialog = false;
		} catch (e) {
			console.error('Error al eliminar:', e);
			toast.error('Error al eliminar las partes');
		} finally {
			isLoading = false;
		}
	}
</script>

<div
	class="flex flex-col gap-6 p-6 h-[calc(100svh-4rem)] group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)] overflow-hidden"
>
	<div class="flex-none flex items-center justify-between">
		<div class="space-y-1">
			<h1 class="text-2xl font-bold tracking-tight">Catálogo de Partes</h1>
			<p class="text-muted-foreground">
				Gestiona y consulta las partes de inventario y activo fijo
			</p>
		</div>
		<div class="flex items-center gap-3">
			<Button variant="outline" size="sm" class="h-9" onclick={handleRefresh}>
				<RefreshCw class="mr-2 h-4 w-4" />
				Actualizar
			</Button>
			{#if !isError && canCreate}
				<Button class="h-9" href="/dashboard/goods/parts/edit/new">
					<Plus class="mr-2 h-4 w-4" />
					Nueva Parte
				</Button>
			{/if}
		</div>
	</div>

	{#if isError}
		<ErrorState
			status={!canView ? 403 : status}
			error={!canView ? 'Permission denied: goods_parts.view' : error || ''}
			onRetry={loadData}
		/>
	{:else}
		{#if error}
			<div
				class="flex-none rounded-md border border-destructive px-4 py-3 text-sm text-destructive"
			>
				{error}
			</div>
		{/if}

		<div class="flex min-h-0 flex-1 gap-4 overflow-hidden">
			<!-- Panel izquierdo: Grid/Tabla de partes -->
			<div class="flex min-h-0 flex-1 flex-col gap-4 overflow-hidden">
				<div class="rounded-md border bg-background">
					<div class="space-y-4 p-4">
						<div class="flex items-center justify-between">
							<h2 class="text-sm font-semibold">Filtros</h2>
							<span class="text-xs text-muted-foreground">
								Filtra las partes por diferentes criterios (los filtros se aplican automáticamente)
							</span>
						</div>
						<div class="grid grid-cols-3 gap-4">
							<div class="space-y-2">
								<Label class="text-xs">Número de Parte</Label>
								<Input
									bind:value={searchPartNumber}
									placeholder="Ej: PART-001"
									class="h-9 bg-card"
								/>
							</div>
							<div class="space-y-2">
								<Label class="text-xs">Descripción</Label>
								<Input
									bind:value={searchDescription}
									placeholder="Buscar descripción..."
									class="h-9 bg-card"
								/>
							</div>
							<div class="space-y-2">
								<Label class="text-xs">Clase</Label>
								<Input bind:value={searchClass} placeholder="Clase..." class="h-9 bg-card" />
							</div>
						</div>
					</div>
				</div>

				<div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border bg-background">
					<div class="flex items-center justify-between border-b bg-background/95 p-3">
						<h2 class="text-sm font-semibold">Listado de Partes</h2>
						<div class="flex items-center gap-2">
							<span class="text-xs text-muted-foreground">
								Mostrando {filteredParts.length} registros {selectedParts.length > 0
									? `(${selectedParts.length} seleccionados)`
									: ''}
							</span>
							<Button variant="outline" size="sm" class="h-9" onclick={handleRefresh}>
								<RefreshCw class="mr-2 h-4 w-4" />
								Actualizar
							</Button>
						</div>
					</div>

					<div class="flex min-h-0 flex-1 flex-col overflow-hidden p-0">
						<div class="min-h-0 flex-1 overflow-hidden">
							<DataTable
								data={filteredParts}
								{columns}
								loading={isLoading}
								hasMore={false}
								loadMore={() => {}}
								{sorting}
								onSortingChange={(newSorting) => (sorting = newSorting)}
								bind:rowSelection
								onRowDoubleClick={(part) => {
									if (!canEdit) {
										toast.error('No tienes permiso para editar partes');
										return;
									}
									goto(`/dashboard/goods/parts/edit/${part.id}`);
								}}
							/>
						</div>
					</div>
				</div>
			</div>

			<!-- Panel derecho: Detalles -->
			<div
				class="flex w-96 flex-none flex-col overflow-hidden rounded-xl border bg-muted/30 shadow-sm"
			>
				{#if selectedParts.length > 1}
					<!-- Vista de Multi-Selección -->
					<div class="border-b p-4">
						<p class="text-[10px] tracking-widest text-muted-foreground uppercase opacity-80">
							Selección Múltiple
						</p>
						<div class="flex items-center gap-2 mt-1">
							<h2 class="font-mono text-3xl font-black tracking-tighter text-primary">
								{selectedParts.length}
							</h2>
							<span class="text-sm font-semibold text-muted-foreground">Partes seleccionadas</span>
						</div>
					</div>
					<div
						class="flex flex-1 flex-col items-center justify-center space-y-4 p-6 bg-card text-center text-muted-foreground"
					>
						<CheckSquare class="h-16 w-16 opacity-20" />
						<p class="text-sm">
							Tienes múltiples partes seleccionadas.<br />
							Las acciones en lote aplicarán a todos los registros marcados.
						</p>
					</div>
				{:else if activePart}
					<!-- Vista de Selección Única -->
					<div class="border-b p-4">
						<p class="text-[10px] tracking-widest text-muted-foreground uppercase opacity-80">
							Número de Parte
						</p>
						<div class="flex flex-wrap items-center gap-2">
							<h2 class="font-mono text-3xl font-black tracking-tighter">
								{activePart.part_number || '---'}
							</h2>
							{#if activePart.inv_data && activePart.fa_data}
								<span
									class="rounded-full border border-purple-200 bg-purple-50 px-2 py-0.5 text-[10px] font-bold tracking-wider text-purple-700 uppercase"
								>
									AMBOS
								</span>
							{:else if activePart.inv_data}
								<span
									class="rounded-full border border-sky-200 bg-sky-50 px-2 py-0.5 text-[10px] font-bold tracking-wider text-sky-700 uppercase"
								>
									SCAI
								</span>
							{:else if activePart.fa_data}
								<span
									class="rounded-full border border-amber-200 bg-amber-50 px-2 py-0.5 text-[10px] font-bold tracking-wider text-amber-700 uppercase"
								>
									SCAF
								</span>
							{/if}
						</div>
					</div>

					<div class="flex-1 space-y-6 overflow-auto bg-card p-5">
						<div class="space-y-3">
							<div>
								<Label class="text-[10px] font-bold text-muted-foreground uppercase"
									>Descripción ES</Label
								>
								<p class="text-sm leading-tight font-semibold">
									{activePart.description_spanish || 'Sin descripción'}
								</p>
							</div>
							<div class="border-t border-dashed pt-2">
								<Label class="text-[10px] font-bold text-muted-foreground uppercase"
									>Description EN</Label
								>
								<p class="text-sm text-muted-foreground italic">
									{activePart.description_english || 'No translation available'}
								</p>
							</div>
						</div>

						<div class="grid grid-cols-2 gap-4 border-t pt-4">
							<div class="space-y-1">
								<Label class="text-[10px] font-bold text-muted-foreground uppercase">Clase</Label>
								<div class="flex items-center gap-2">
									<Folder class="h-3 w-3 text-blue-500" />
									<span class="text-sm font-bold">{activePart.part_class || '-'}</span>
								</div>
							</div>
							<div class="space-y-1">
								<Label class="text-[10px] font-bold text-muted-foreground uppercase">U.M.</Label>
								<span class="text-sm font-bold">{activePart.unit_of_measure || '-'}</span>
							</div>
							<div class="space-y-1">
								<Label class="text-[10px] font-bold text-muted-foreground uppercase"
									>Peso Unit.</Label
								>
								<span class="text-sm font-bold">{activePart.unit_weight || '-'}</span>
							</div>
						</div>

						<div
							class="rounded-lg border border-orange-100 bg-orange-50 p-3 dark:border-orange-900 dark:bg-orange-950/20"
						>
							<Label class="text-[10px] font-bold text-orange-600 uppercase dark:text-orange-400">
								Fracción Arancelaria
							</Label>
							<p class="font-mono text-lg font-bold text-orange-700 dark:text-orange-300">
								{formatMexTariffDigitsForDisplay(activePart.fraction || '') || '0000.00.00'}
							</p>
						</div>

						{#if activePart.unit_cost}
							<div
								class="rounded-lg border border-green-100 bg-green-50 p-3 dark:border-green-900 dark:bg-green-950/20"
							>
								<Label class="text-[10px] font-bold text-green-600 uppercase dark:text-green-400">
									Costo Unitario
								</Label>
								<p class="text-lg font-bold text-green-700 dark:text-green-300">
									${activePart.unit_cost}
									{activePart.currency_key || 'USD'}
								</p>
							</div>
						{/if}
					</div>
				{:else}
					<!-- Vista Vacía -->
					<div
						class="flex h-full flex-col items-center justify-center text-center text-muted-foreground"
					>
						<Package class="mb-3 h-12 w-12 opacity-20" />
						<p class="text-sm">Selecciona una o más partes para ver sus detalles</p>
					</div>
				{/if}
			</div>
		</div>
	{/if}
</div>

<div class="h-20"></div>

<!-- Footer fijo con botones de acción -->
{#if !isError}
	<div
		class="fixed right-0 bottom-0 left-0 z-[5] 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 canCreate}
					<Button size="sm" href="/dashboard/goods/parts/edit/new">
						<Plus class="mr-1 h-4 w-4" />
						Insertar
					</Button>
				{/if}

				{#if canEdit}
					<Button
						variant="outline"
						size="sm"
						href={activePart ? `/dashboard/goods/parts/edit/${activePart.id}` : '#'}
						disabled={selectedParts.length !== 1}
					>
						Editar {selectedParts.length > 1 ? '(Solo 1)' : ''}
					</Button>
				{/if}

				{#if canDelete}
					<Button
						variant="outline"
						size="sm"
						onclick={handleDelete}
						disabled={selectedParts.length === 0}
					>
						Borrar {selectedParts.length > 1 ? `(${selectedParts.length})` : ''}
					</Button>
				{/if}
			</div>
		</div>
	</div>
{/if}

<!-- Dialog de confirmación para borrar -->
<Dialog.Root bind:open={showDeleteDialog}>
	<Dialog.Content class="max-w-md">
		<Dialog.Header>
			<Dialog.Title>¿Confirmar eliminación?</Dialog.Title>
		</Dialog.Header>
		<div class="py-4">
			{#if selectedParts.length === 1}
				<p class="text-sm text-muted-foreground">
					¿Estás seguro que deseas eliminar la parte <strong class="text-foreground"
						>{activePart?.part_number}</strong
					>?
				</p>
				<p class="mt-2 text-sm text-muted-foreground">
					{activePart?.description_spanish}
				</p>
			{:else}
				<p class="text-sm text-muted-foreground">
					¿Estás seguro que deseas eliminar las <strong class="text-foreground"
						>{selectedParts.length} partes seleccionadas</strong
					>?
				</p>
			{/if}
			<p class="mt-4 text-sm text-destructive">Esta acción no se puede deshacer.</p>
		</div>
		<Dialog.Footer>
			<Button variant="outline" onclick={() => (showDeleteDialog = false)}>Cancelar</Button>
			<Button variant="destructive" disabled={isLoading} onclick={confirmDelete}>
				{#if isLoading}
					<RefreshCw class="mr-2 h-4 w-4 animate-spin" />
					Eliminando...
				{:else}
					Eliminar
				{/if}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
