<script lang="ts">
	import * as Dialog from '$lib/components/ui/dialog';
	import * as Table from '$lib/components/ui/table';
	import { Input } from '$lib/components/ui/input';
	import { Button } from '$lib/components/ui/button';
	import { Search, Loader2 } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';

	let {
		open = $bindable(false),
		onSelect
	}: {
		open?: boolean;
		onSelect?: (classItem: any) => void;
	} = $props();

	let searchQuery = $state('');
	let isSearching = $state(false);
	let classes = $state<any[]>([]);
	let displayedClasses = $state<any[]>([]);
	let currentPage = $state(1);
	let itemsPerPage = 10;

	const filteredClasses = $derived(
		searchQuery
			? classes.filter(
					(c) =>
						c.class_code?.toLowerCase().includes(searchQuery.toLowerCase()) ||
						c.description_es?.toLowerCase().includes(searchQuery.toLowerCase())
				)
			: classes
	);

	$effect(() => {
		if (open) {
			searchClasses();
		}
	});

	$effect(() => {
		currentPage = 1;
		loadMoreClasses();
	});

	async function searchClasses() {
		const activeCompanyId = companyStore?.activeCompany?.id;
		if (!activeCompanyId) {
			toast.error('No hay compañía activa');
			return;
		}

		isSearching = true;
		try {
			const response = await fetch(
				`/api-sveltekit/classes?company_id=${activeCompanyId}&limit=100`,
				{
					method: 'GET',
					headers: {
						'Content-Type': 'application/json'
					}
				}
			);

			if (!response.ok) {
				throw new Error('Error al buscar clases');
			}

			const data = await response.json();
			classes = data.items || [];
			loadMoreClasses();
		} catch (error) {
			console.error('Error searching classes:', error);
			toast.error('Error al buscar clases');
			classes = [];
		} finally {
			isSearching = false;
		}
	}

	function loadMoreClasses() {
		const start = 0;
		const end = currentPage * itemsPerPage;
		displayedClasses = filteredClasses.slice(start, end);
	}

	function handleScroll(e: Event) {
		const target = e.target as HTMLDivElement;
		const threshold = 100;
		const scrolledToBottom =
			target.scrollHeight - target.scrollTop - target.clientHeight < threshold;

		if (scrolledToBottom && displayedClasses.length < filteredClasses.length) {
			currentPage++;
			loadMoreClasses();
		}
	}

	function handleSelect(classItem: any) {
		if (onSelect) {
			onSelect(classItem);
		}
		open = false;
	}
</script>

<Dialog.Root bind:open>
	<Dialog.Content class="max-w-4xl max-h-[80vh] flex flex-col">
		<Dialog.Header>
			<Dialog.Title>Seleccionar Clase</Dialog.Title>
			<Dialog.Description>Busca y selecciona una clase para la partida</Dialog.Description>
		</Dialog.Header>

		<div class="flex gap-2 mb-4">
			<div class="relative flex-1">
				<Search class="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
				<Input
					placeholder="Buscar por código o descripción..."
					bind:value={searchQuery}
					class="pl-8"
				/>
			</div>
		</div>

		<div class="flex-1 overflow-auto border rounded-md" onscroll={handleScroll}>
			{#if isSearching}
				<div class="flex items-center justify-center py-8">
					<Loader2 class="w-6 h-6 animate-spin text-muted-foreground" />
				</div>
			{:else}
				<Table.Root>
					<Table.Header class="sticky top-0 bg-background z-10">
						<Table.Row>
							<Table.Head class="w-[120px]">Código</Table.Head>
							<Table.Head>Descripción</Table.Head>
							<Table.Head class="w-[100px]">U.M.</Table.Head>
							<Table.Head class="w-[100px]"></Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#if displayedClasses.length === 0}
							<Table.Row>
								<Table.Cell colspan={4} class="text-center py-8 text-muted-foreground">
									No se encontraron clases
								</Table.Cell>
							</Table.Row>
						{:else}
							{#each displayedClasses as classItem}
								<Table.Row
									class="cursor-pointer hover:bg-muted/50"
									onclick={() => handleSelect(classItem)}
								>
									<Table.Cell class="font-medium">{classItem.class_code}</Table.Cell>
									<Table.Cell
										>{classItem.description_es || classItem.description_en || '-'}</Table.Cell
									>
									<Table.Cell>{classItem.unit_of_measure || '-'}</Table.Cell>
									<Table.Cell>
										<Button size="sm" variant="ghost" onclick={() => handleSelect(classItem)}>
											Seleccionar
										</Button>
									</Table.Cell>
								</Table.Row>
							{/each}
						{/if}
					</Table.Body>
				</Table.Root>
			{/if}
		</div>

		<Dialog.Footer>
			<Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
