<script lang="ts">
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { companyStore } from '$lib/stores/company.svelte';
	import * as Card from '$lib/components/ui/card';
	import * as Table from '$lib/components/ui/table';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Badge } from '$lib/components/ui/badge';
	import {
		Plus,
		RefreshCw,
		FileText,
		Pencil,
		Trash2,
		Search,
		Filter,
		Building2,
		Globe,
		Box,
		CheckSquare,
		Square,
		AlertCircle
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { cn } from '$lib/utils';

	let fdaList = $state<any[]>([]);
	let loading = $state(false);
	let selectedRows = $state<number[]>([]);
	let mounted = $state(false);
	let searchQuery = $state('');
	let hoveredRow = $state<number | null>(null);

	onMount(() => {
		mounted = true;
	});

	$effect(() => {
		const companyId = companyStore.activeCompany?.id;
		if (mounted && companyId) {
			fdaList = [];
			loadAllFdaData();
		}
	});

	// Filtrar por búsqueda
	const filteredFdaList = $derived(
		searchQuery.trim()
			? fdaList.filter(
					(fda) =>
						fda.fda_key?.toLowerCase().includes(searchQuery.toLowerCase()) ||
						fda.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
						fda.fda_code?.toLowerCase().includes(searchQuery.toLowerCase()) ||
						fda.country_of_production?.toLowerCase().includes(searchQuery.toLowerCase())
				)
			: fdaList
	);

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

		loading = true;
		try {
			const res = await fetch(`/api-sveltekit/fda-catalog?company_id=${companyId}`);
			if (res.ok) {
				const data = await res.json();
				fdaList = data.items || [];
				selectedRows = [];
			}
		} catch (error) {
			console.error('Error cargando lista de FDA:', error);
		} finally {
			loading = false;
		}
	}

	function handleCreateClick() {
		goto('/dashboard/goods/fda-codes/edit/new');
	}

	function handleEditClick(fdaId: number) {
		goto(`/dashboard/goods/fda-codes/edit/${fdaId}`);
	}

	async function deleteFdaCode(id: number, event?: MouseEvent) {
		event?.stopPropagation();
		if (!confirm('¿Está seguro de eliminar este código FDA?')) return;

		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		try {
			const res = await fetch(`/api-sveltekit/fda-catalog?id=${id}&company_id=${companyId}`, {
				method: 'DELETE'
			});
			if (res.ok) {
				toast.success('Registro eliminado correctamente');
				selectedRows = selectedRows.filter((r) => r !== id);
				fdaList = fdaList.filter((f) => f.id !== id);
			} else {
				const error = await res.json();
				toast.error(error.error || 'Error al eliminar');
			}
		} catch (err) {
			console.error('Error:', err);
			toast.error('Error de conexión');
		}
	}

	function toggleRowSelection(id: number) {
		if (selectedRows.includes(id)) {
			selectedRows = selectedRows.filter((r) => r !== id);
		} else {
			selectedRows = [...selectedRows, id];
		}
	}

	function toggleAllSelection(checked: boolean) {
		if (checked) {
			selectedRows = filteredFdaList.map((row) => row.id);
		} else {
			selectedRows = [];
		}
	}

	async function handleDeleteSelected() {
		if (selectedRows.length === 0) return;

		if (!confirm(`¿Está seguro de eliminar ${selectedRows.length} código(s) FDA?`)) return;

		for (const id of selectedRows) {
			await deleteFdaCode(id);
		}
	}

	function handleEditSelected() {
		if (selectedRows.length !== 1) return;
		const id = selectedRows[0];
		handleEditClick(id);
	}

	function clearSelection() {
		selectedRows = [];
	}

	// Obtener badge de estado de almacenaje
	function getStorageBadge(status: string) {
		const styles: Record<string, string> = {
			ACTIVO: 'bg-green-100 text-green-700 border-green-200',
			INACTIVO: 'bg-gray-100 text-gray-700 border-gray-200',
			PENDIENTE: 'bg-yellow-100 text-yellow-700 border-yellow-200'
		};
		return styles[status?.toUpperCase()] || 'bg-blue-100 text-blue-700 border-blue-200';
	}
</script>

<div class="min-h-screen bg-gradient-to-b from-background to-muted/20 pb-28">
	<!-- Header Principal -->
	<div class="sticky top-0 z-20 border-b bg-card/50 backdrop-blur-sm">
		<div class="mx-auto max-w-[1600px] px-4 py-6 sm:px-6">
			<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
				<div class="space-y-1">
					<div class="flex items-center gap-3">
						<div class="rounded-lg bg-primary/10 p-2">
							<FileText class="h-6 w-6 text-primary" />
						</div>
						<h1 class="text-2xl font-bold tracking-tight sm:text-3xl">Códigos F.D.A.</h1>
					</div>
					<p class="pl-[52px] text-sm text-muted-foreground sm:text-base">
						Gestión de códigos FDA para mercancías / FDA goods code management
					</p>
				</div>
				<div class="flex items-center gap-2 sm:gap-3">
					<Button
						variant="outline"
						size="sm"
						onclick={loadAllFdaData}
						disabled={loading}
						class="h-10"
					>
						<RefreshCw class="mr-2 h-4 w-4 {loading ? 'animate-spin' : ''}" />
						<span class="hidden sm:inline">Actualizar</span>
					</Button>
					<Button onclick={handleCreateClick} size="sm" class="h-10 shadow-lg shadow-primary/20">
						<Plus class="mr-2 h-4 w-4" />
						<span class="hidden sm:inline">Nuevo Código</span>
						<span class="sm:hidden">Nuevo</span>
					</Button>
				</div>
			</div>
		</div>
	</div>

	<!-- Contenido Principal -->
	<div class="mx-auto max-w-[1600px] px-4 py-6 sm:px-6">
		<Card.Root class="overflow-hidden border-0 shadow-xl shadow-black/5">
			<!-- Header de Tabla con Búsqueda -->
			<div class="border-b bg-muted/30 p-4 sm:p-6">
				<div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
					<div class="flex items-center gap-3">
						<div class="rounded-lg bg-primary/10 p-2">
							<Filter class="h-4 w-4 text-primary" />
						</div>
						<div>
							<h3 class="text-lg font-semibold">Registros FDA</h3>
							<p class="text-sm text-muted-foreground">
								{filteredFdaList.length} de {fdaList.length} registros
							</p>
						</div>
					</div>

					<div class="relative w-full sm:w-80">
						<Search
							class="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-muted-foreground"
						/>
						<Input
							type="text"
							placeholder="Buscar por clave, código, descripción..."
							bind:value={searchQuery}
							class="h-10 bg-background pl-10"
						/>
					</div>
				</div>

				<!-- Barra de selección -->
				{#if selectedRows.length > 0}
					<div
						class="animate-in fade-in slide-in-from-top-2 mt-4 flex items-center justify-between rounded-lg border border-primary/20 bg-primary/5 p-3"
					>
						<div class="flex items-center gap-3">
							<CheckSquare class="h-5 w-5 text-primary" />
							<span class="text-sm font-medium">
								{selectedRows.length}
								{selectedRows.length === 1 ? 'registro seleccionado' : 'registros seleccionados'}
							</span>
						</div>
						<Button variant="ghost" size="sm" onclick={clearSelection} class="h-8">
							Limpiar selección
						</Button>
					</div>
				{/if}
			</div>

			<!-- Tabla -->
			<div class="overflow-x-auto">
				<Table.Root>
					<Table.Header>
						<Table.Row class="bg-muted/50 hover:bg-muted/50">
							<Table.Head class="w-12 text-center">
								<Checkbox
									checked={filteredFdaList.length > 0 &&
										selectedRows.length === filteredFdaList.length}
									indeterminate={selectedRows.length > 0 &&
										selectedRows.length < filteredFdaList.length}
									onCheckedChange={toggleAllSelection}
									aria-label="Seleccionar todos"
								/>
							</Table.Head>
							<Table.Head class="font-semibold whitespace-nowrap">Clave FDA</Table.Head>
							<Table.Head class="font-semibold">Descripción</Table.Head>
							<Table.Head class="font-semibold whitespace-nowrap">Código FDA</Table.Head>
							<Table.Head class="font-semibold whitespace-nowrap">Fabricante</Table.Head>
							<Table.Head class="font-semibold whitespace-nowrap">País</Table.Head>
							<Table.Head class="font-semibold whitespace-nowrap">Estado</Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#if loading}
							<Table.Row>
								<Table.Cell colspan={7} class="py-16 text-center">
									<div class="flex flex-col items-center gap-4">
										<div class="rounded-full bg-primary/10 p-4">
											<RefreshCw class="h-8 w-8 animate-spin text-primary" />
										</div>
										<div>
											<p class="text-lg font-medium">Cargando registros...</p>
											<p class="text-sm text-muted-foreground">Por favor espere</p>
										</div>
									</div>
								</Table.Cell>
							</Table.Row>
						{:else if filteredFdaList.length === 0}
							<Table.Row>
								<Table.Cell colspan={7} class="py-16 text-center">
									{#if searchQuery}
										<div class="flex flex-col items-center gap-4">
											<div class="rounded-full bg-muted p-4">
												<Search class="h-8 w-8 text-muted-foreground" />
											</div>
											<div>
												<p class="text-lg font-medium">No se encontraron resultados</p>
												<p class="text-sm text-muted-foreground">Intenta con otra búsqueda</p>
											</div>
											<Button variant="outline" size="sm" onclick={() => (searchQuery = '')}>
												Limpiar búsqueda
											</Button>
										</div>
									{:else}
										<div class="flex flex-col items-center gap-4">
											<div class="rounded-full bg-muted p-4">
												<Box class="h-8 w-8 text-muted-foreground" />
											</div>
											<div>
												<p class="text-lg font-medium">No hay registros FDA</p>
												<p class="text-sm text-muted-foreground">
													No se encontraron registros para esta compañía
												</p>
											</div>
										</div>
									{/if}
								</Table.Cell>
							</Table.Row>
						{:else}
							{#each filteredFdaList as fda, i (fda.id)}
								<Table.Row
									class={cn(
										'cursor-pointer transition-all duration-150',
										selectedRows.includes(fda.id) && 'bg-primary/5 hover:bg-primary/10',
										hoveredRow === fda.id && !selectedRows.includes(fda.id) && 'bg-muted/30',
										'hover:shadow-sm'
									)}
									onmouseenter={() => (hoveredRow = fda.id)}
									onmouseleave={() => (hoveredRow = null)}
									onclick={() => toggleRowSelection(fda.id)}
								>
									<Table.Cell class="text-center" onclick={(e) => e.stopPropagation()}>
										<Checkbox
											checked={selectedRows.includes(fda.id)}
											onCheckedChange={() => toggleRowSelection(fda.id)}
											aria-label="Seleccionar fila"
										/>
									</Table.Cell>
									<Table.Cell>
										<div class="flex items-center gap-2">
											<span
												class="rounded bg-primary/10 px-2 py-1 font-mono text-sm font-bold text-primary"
											>
												{fda.fda_key}
											</span>
										</div>
									</Table.Cell>
									<Table.Cell>
										<div class="max-w-[300px]">
											<p class="truncate font-medium" title={fda.description}>
												{fda.description || '-'}
											</p>
											{#if fda.requirements}
												<p
													class="mt-0.5 truncate text-xs text-muted-foreground"
													title={fda.requirements}
												>
													{fda.requirements}
												</p>
											{/if}
										</div>
									</Table.Cell>
									<Table.Cell>
										<span class="font-mono text-sm">
											{fda.fda_code || '-'}
										</span>
									</Table.Cell>
									<Table.Cell>
										<div class="flex items-center gap-2">
											<Building2 class="h-3.5 w-3.5 text-muted-foreground" />
											<span class="text-sm">{fda.manufacturer_number || '-'}</span>
										</div>
									</Table.Cell>
									<Table.Cell>
										<div class="flex items-center gap-2">
											<Globe class="h-3.5 w-3.5 text-muted-foreground" />
											<span class="text-sm">{fda.country_of_production || '-'}</span>
										</div>
									</Table.Cell>
									<Table.Cell>
										{#if fda.storage_status}
											<Badge
												variant="outline"
												class={cn('text-xs font-medium', getStorageBadge(fda.storage_status))}
											>
												{fda.storage_status}
											</Badge>
										{:else}
											<span class="text-sm text-muted-foreground">-</span>
										{/if}
									</Table.Cell>
								</Table.Row>
							{/each}
						{/if}
					</Table.Body>
				</Table.Root>
			</div>

				{#if filteredFdaList.length > 0}
					<div class="flex items-center justify-between border-t bg-muted/30 px-4 py-3">
						<span class="text-sm text-muted-foreground">
							Mostrando {filteredFdaList.length} registros
						</span>
						{#if searchQuery}
							<Badge variant="secondary" class="gap-2">
								Filtro: "{searchQuery}"
								<button onclick={() => (searchQuery = '')} class="hover:text-destructive">
									×
								</button>
							</Badge>
						{/if}
					</div>
				{/if}
			</Card.Root>
	</div>


	<!-- Footer Fijo con Acciones -->
	<div
		class="fixed right-0 bottom-0 left-0 z-30 border-t bg-background/95 shadow-[0_-4px_20px_rgba(0,0,0,0.1)] backdrop-blur supports-[backdrop-filter]:bg-background/90"
	>
		<div class="mx-auto max-w-[1600px] px-4 py-4 sm:px-6">
			<div class="flex items-center justify-between">
				<!-- Info de selección -->
				<div class="flex items-center gap-4">
					{#if selectedRows.length > 0}
						<div class="flex items-center gap-3 rounded-full bg-primary/10 px-4 py-2">
							<CheckSquare class="h-4 w-4 text-primary" />
							<span class="text-sm font-semibold text-primary">
								{selectedRows.length} seleccionado(s)
							</span>
						</div>
					{:else}
						<div class="flex items-center gap-2 text-sm text-muted-foreground">
							<AlertCircle class="h-4 w-4" />
							<span>Selecciona registros para editar o eliminar</span>
						</div>
					{/if}
				</div>

				<!-- Botones de acción -->
				<div class="flex items-center gap-2">
					<Button size="default" onclick={handleCreateClick} class="shadow-lg shadow-primary/20">
						<Plus class="mr-2 h-4 w-4" />
						<span class="hidden sm:inline">Insertar</span>
						<span class="sm:hidden">Nuevo</span>
					</Button>
					<Button
						variant="outline"
						size="default"
						disabled={selectedRows.length !== 1}
						onclick={handleEditSelected}
						class={selectedRows.length === 1 ? 'border-primary/50' : ''}
					>
						<Pencil class="mr-2 h-4 w-4" />
						<span class="hidden sm:inline">Editar</span>
					</Button>
					<Button
						variant="outline"
						size="default"
						disabled={selectedRows.length === 0}
						onclick={handleDeleteSelected}
						class={selectedRows.length > 0
							? 'border-destructive/50 text-destructive hover:bg-destructive/10'
							: ''}
					>
						<Trash2 class="mr-2 h-4 w-4" />
						<span class="hidden sm:inline">Borrar</span>
					</Button>
				</div>
			</div>
		</div>
	</div>
</div>
