<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 { Plus, RefreshCw, Package } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { partsApi, type Part } from '$lib/api/dashboard/a76/parts';
	import { clientsProvidersApi } from '$lib/api/dashboard/a76/clients-providers';
	import { companyStore } from '$lib/stores/company.svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosListaMercancias } from '$lib/config/shortcuts/dashboard/goods/list';
	import { goto } from '$app/navigation';

	// Estado de la lista de partes
	let parts = $state<Part[]>([]);
	let clientsMap = $state<Record<number, string>>({}); // Mapa ID -> Nombre
	let selectedPart = $state<Part | null>(null);
	let isLoading = $state(false);
	let searchPartNumber = $state('');
	let searchDescription = $state('');
	let searchClient = $state('');
	let searchClass = $state('');

	// Partes filtradas según búsqueda
	const filteredParts = $derived(
		parts.filter((p) => {
			// Filtro por número de parte
			const matchesPartNumber =
				!searchPartNumber || p.part_number.toLowerCase().includes(searchPartNumber.toLowerCase());

			// Filtro por descripción (español o inglés)
			const matchesDescription =
				!searchDescription ||
				(p.description_spanish?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false) ||
				(p.description_english?.toLowerCase().includes(searchDescription.toLowerCase()) ?? false);

			// Filtro por cliente (Busca en nombre o ID)
			const clientName = clientsMap[p.client_id] || '';
			const matchesClient =
				!searchClient ||
				(p.client_id?.toString().includes(searchClient) ?? false) ||
				clientName.toLowerCase().includes(searchClient.toLowerCase());

			// Filtro por clase
			const matchesClass =
				!searchClass || (p.part_class?.toLowerCase().includes(searchClass.toLowerCase()) ?? false);

			return matchesPartNumber && matchesDescription && matchesClient && matchesClass;
		})
	);
	// Reactively load parts when company changes
	$effect(() => {
		const companyId = companyStore.activeCompany?.id;
		if (companyId) {
			loadData();
		}
	});

	// Shortcuts
	useShortcuts(
		'Goods List',
		obtenerAtajosListaMercancias({
			crear: () => goto('/dashboard/goods/parts/edit/new'),
			recargar: loadData,
			editar: () => {
				if (selectedPart?.id) goto(`/dashboard/goods/parts/edit/${selectedPart.id}`);
				else toast.info('Seleccione una parte para editar');
			},
			eliminar: () => {
				if (selectedPart?.id)
					handleDeleteClick(selectedPart.id); // Assuming this function exists or I need to create/find it
				else toast.info('Seleccione una parte para eliminar');
			}
		})
	);

	async function loadData() {
		await Promise.all([loadParts(), loadClients()]);
	}

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

		try {
			// Fetch all clients/providers to ensure we map "both" types as well
			const response = await clientsProvidersApi.list(companyId, 1, 1000);

			const data = (response as any).data || response;
			const items = data.items || [];

			const map: Record<number, string> = {};
			items.forEach((c: any) => {
				map[c.id] = c.name;
			});
			clientsMap = map;
		} catch (e) {
			console.error('Error cargando clientes:', e);
		}
	}

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

		isLoading = true;
		try {
			const response = await partsApi.list({
				company_id: companyId,
				page: 1,
				page_size: 1000
			});

			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;
		}
	}

	function selectPart(part: Part) {
		selectedPart = part;
	}

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

	async function handleDelete() {
		if (!selectedPart) {
			toast.error('Selecciona una parte para borrar');
			return;
		}

		const confirmed = window.confirm(
			`¿Estás seguro de que deseas eliminar la parte ${selectedPart.part_number}? Esta acción no se puede deshacer.`
		);
		if (!confirmed) return;

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

			await partsApi.delete(selectedPart.id, companyId);
			toast.success('Parte eliminada exitosamente');
			selectedPart = null;
			await loadData();
		} catch (e) {
			console.error('Error al eliminar:', e);
			toast.error('Error al eliminar la parte');
		} finally {
			isLoading = false;
		}
	}

	// Keyboard Shortcuts
	useShortcuts('Goods / Parts', [
		{
			key: 'Alt+Shift+N',
			description: 'New Part',
			action: () => goto('/dashboard/goods/parts/edit')
		},
		{
			key: 'Alt+Shift+R',
			description: 'Refresh List',
			action: handleRefresh
		},
		{
			key: 'Alt+Shift+D',
			description: 'Delete Selected',
			action: handleDelete
		}
	]);
</script>

<div class="flex flex-col h-[calc(100vh-4rem)] p-4 gap-4 pb-15">
	<!-- Título -->
	<div class="flex flex-col gap-1">
		<h1 class="text-2xl font-bold">CATÁLOGO DE PARTES</h1>
		<p class="text-sm text-muted-foreground">
			Gestiona y consulta las partes de inventario y activo fijo
		</p>
	</div>

	<!-- Contenedor principal con grid y detalles -->
	<div class="flex-1 flex gap-4 overflow-hidden">
		<!-- Panel izquierdo: Grid/Tabla de partes -->
		<div class="flex-1 flex flex-col gap-4 overflow-hidden">
			<!-- Sección de Filtros -->
			<div class="border rounded-lg bg-card">
				<div class="p-4 space-y-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-4 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" />
						</div>
						<div class="space-y-2">
							<Label class="text-xs">Descripción</Label>
							<Input
								bind:value={searchDescription}
								placeholder="Buscar descripción..."
								class="h-9"
							/>
						</div>
						<div class="space-y-2">
							<Label class="text-xs">Cliente</Label>
							<Input bind:value={searchClient} placeholder="Nombre o ID..." class="h-9" />
						</div>
						<div class="space-y-2">
							<Label class="text-xs">Clase</Label>
							<Input bind:value={searchClass} placeholder="Clase..." class="h-9" />
						</div>
					</div>
				</div>
			</div>

			<!-- Tabla de partes -->
			<div class="flex-1 flex flex-col border rounded-lg overflow-hidden">
				<div class="flex items-center justify-between p-3 border-b bg-white dark:bg-muted/50">
					<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
						</span>
						<Button variant="outline" size="sm" onclick={handleRefresh}>
							<RefreshCw class="h-4 w-4 mr-2" />
							Actualizar
						</Button>
					</div>
				</div>

				<!-- Tabla de partes -->
				<div class="flex-1 overflow-auto">
					<table class="w-full text-sm">
						<thead class="bg-white dark:bg-black text-gray-900 dark:text-white border-b">
							<tr>
								<th class="px-2 py-2 text-left w-8">
									<input type="checkbox" class="h-4 w-4" />
								</th>
								<th class="px-2 py-2 text-left">Número de Parte</th>
								<th class="px-2 py-2 text-left">Descripción</th>
								<th class="px-2 py-2 text-left">Cliente</th>
								<th class="px-2 py-2 text-left">Clase</th>
								<th class="px-2 py-2 text-left">U.M.</th>
								<th class="px-2 py-2 text-left">Fracción</th>
							</tr>
						</thead>
						<tbody>
							{#if isLoading}
								<tr>
									<td colspan="7" class="text-center py-8 text-muted-foreground">Cargando...</td>
								</tr>
							{:else if filteredParts.length === 0}
								<tr>
									<td colspan="7" class="text-center py-8 text-muted-foreground">
										No hay partes registradas
									</td>
								</tr>
							{:else}
								{#each filteredParts as part (part.id)}
									<tr
										class="border-b cursor-pointer transition-colors {selectedPart?.id === part.id
											? 'bg-gray-300 dark:bg-gray-600'
											: 'hover:bg-gray-100 dark:hover:bg-gray-700'}"
										onclick={() => selectPart(part)}
									>
										<td class="px-2 py-1">
											<input
												type="checkbox"
												checked={selectedPart?.id === part.id}
												class="h-4 w-4"
											/>
										</td>
										<td class="px-2 py-1">
											<span
												class="inline-flex items-center rounded-md bg-blue-50 dark:bg-blue-900/30 px-2 py-1 text-xs font-mono font-bold text-blue-700 dark:text-blue-400 border border-blue-200 dark:border-blue-800"
											>
												{part.part_number}
											</span>
										</td>
										<td class="px-2 py-1 font-medium text-sm">{part.description_spanish || ''}</td>
										<td class="px-2 py-1 text-muted-foreground">
											<div class="flex flex-col">
												<span class="font-medium text-xs"
													>{clientsMap[part.client_id] || 'Cargando...'}</span
												>
											</div>
										</td>
										<td class="px-2 py-1">
											{#if part.part_class}
												<span
													class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-400"
												>
													{part.part_class}
												</span>
											{:else}
												<span class="text-muted-foreground">-</span>
											{/if}
										</td>
										<td class="px-2 py-1 text-muted-foreground">{part.unit_of_measure || '-'}</td>
										<td class="px-2 py-1 font-mono text-xs text-orange-600 dark:text-orange-400"
											>{part.fraction || '-'}</td
										>
									</tr>
								{/each}
							{/if}
						</tbody>
					</table>
				</div>
			</div>
		</div>

		<!-- Panel derecho: Detalles y edición -->
		<div
			class="w-96 flex-none flex flex-col border rounded-xl bg-muted/30 shadow-sm overflow-hidden"
		>
			<div class="p-4 border-b">
				<p class="text-[10px] uppercase tracking-widest opacity-80 text-muted-foreground">
					Número de Parte
				</p>
				<h2 class="text-3xl font-black font-mono tracking-tighter">
					{selectedPart?.part_number || '---'}
				</h2>
			</div>

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

					<div class="grid grid-cols-2 gap-4 pt-4 border-t">
						<div class="space-y-1">
							<Label class="text-[10px] uppercase text-muted-foreground font-bold">Cliente</Label>
							<div class="flex items-center gap-2">
								<Package class="h-3 w-3 text-blue-500" />
								<span class="text-sm font-bold"
									>{clientsMap[selectedPart.client_id] || selectedPart.client_id}</span
								>
							</div>
						</div>
						<div class="space-y-1">
							<Label class="text-[10px] uppercase text-muted-foreground font-bold">Clase</Label>
							<span class="text-sm font-bold">{selectedPart.part_class || '-'}</span>
						</div>
					</div>

					<div class="grid grid-cols-2 gap-4">
						<div class="space-y-1">
							<Label class="text-[10px] uppercase text-muted-foreground font-bold">U.M.</Label>
							<span class="text-sm font-bold">{selectedPart.unit_of_measure || '-'}</span>
						</div>
						<div class="space-y-1">
							<Label class="text-[10px] uppercase text-muted-foreground font-bold">Peso Unit.</Label
							>
							<span class="text-sm font-bold">{selectedPart.unit_weight || '-'}</span>
						</div>
					</div>

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

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

<!-- Footer fijo con botones de acción -->
<div
	class="fixed bottom-0 left-0 right-0 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 border-t shadow-lg z-[5] group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] ml-[calc(var(--sidebar-width))]"
>
	<div class="px-4 py-4 max-w-[1400px] mx-auto">
		<!-- Botones de acción -->
		<div class="flex justify-end gap-2">
			<Button size="sm" href="/dashboard/goods/parts/edit">
				<Plus class="h-4 w-4 mr-1" />
				Nueva Parte
			</Button>
			<Button
				variant="outline"
				size="sm"
				href="/dashboard/goods/parts/edit/{selectedPart?.id}"
				disabled={!selectedPart}>Editar</Button
			>
			<Button variant="outline" size="sm" onclick={handleDelete} disabled={!selectedPart}
				>Borrar</Button
			>
		</div>
	</div>
</div>
