<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Search, Loader2, User, Building2 } from 'lucide-svelte';
	import {
		clientsProvidersApi,
		type ClientProvider
	} from '$lib/api/dashboard/a76/clients-providers';
	import { companyStore } from '$lib/stores/company.svelte';

	let {
		open = $bindable(false),
		onSelect,
		onClear
	}: {
		open: boolean;
		onSelect: (provider: ClientProvider) => void;
		onClear?: () => void;
	} = $props();

	let providers = $state<ClientProvider[]>([]);
	let loading = $state(false);
	let searchTerm = $state('');
	let loaded = $state(false);

	let filteredProviders = $derived(
		providers.filter(
			(p) =>
				(p.client_or_provider === 'provider' || p.client_or_provider === 'both') &&
				(p.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
					p.rfc.toLowerCase().includes(searchTerm.toLowerCase()) ||
					p.id.toString().includes(searchTerm))
		)
	);

	$effect(() => {
		if (open && !loaded && companyStore.activeCompany?.id) {
			loadProviders();
		}
	});

	async function loadProviders() {
		if (!companyStore.activeCompany?.id) return;

		loading = true;
		try {
			const res = await clientsProvidersApi.list(companyStore.activeCompany.id, 1, 1000);
			const responseData = (res as any).data || res;

			if (responseData && responseData.items) {
				providers = responseData.items;
				loaded = true;
			}
		} catch (e) {
			console.error('Error cargando proveedores:', e);
		} finally {
			loading = false;
		}
	}

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

<Dialog.Root bind:open>
	<Dialog.Content class="sm:max-w-[700px] max-h-[80vh] flex flex-col z-[300]">
		<Dialog.Header>
			<Dialog.Title>Seleccionar Proveedor (Textil)</Dialog.Title>
			<Dialog.Description>
				Busca y selecciona el proveedor para el material textil.
			</Dialog.Description>
		</Dialog.Header>

		<div class="relative w-full my-2">
			<Search class="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
			<Input
				type="search"
				placeholder="Buscar por Nombre, RFC o ID..."
				class="pl-9"
				bind:value={searchTerm}
			/>
		</div>

		<div class="flex-1 overflow-y-auto border rounded-md min-h-[300px]">
			{#if loading}
				<div class="flex flex-col items-center justify-center h-48 gap-2 text-muted-foreground">
					<Loader2 class="h-8 w-8 animate-spin text-primary" />
					<p>Cargando catálogo...</p>
				</div>
			{:else if filteredProviders.length === 0}
				<div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
					<p>No se encontraron proveedores.</p>
				</div>
			{:else}
				<table class="w-full text-sm">
					<thead class="bg-muted/50 backdrop-blur-sm">
						<tr class="text-left border-b">
							<th class="p-3 font-medium text-muted-foreground w-[60px]">ID</th>
							<th class="p-3 font-medium text-muted-foreground w-[130px]">RFC</th>
							<th class="p-3 font-medium text-muted-foreground">Nombre</th>
						</tr>
					</thead>
					<tbody>
						{#each filteredProviders as provider}
							<tr
								class="border-b hover:bg-accent/50 transition-colors cursor-pointer"
								onclick={() => handleSelect(provider)}
							>
								<td class="p-3 font-mono text-xs">{provider.id}</td>
								<td class="p-3 font-mono text-xs">{provider.rfc}</td>
								<td class="p-3 font-medium">
									<div class="flex items-center gap-2">
										<Building2 class="h-3 w-3 text-purple-500" />
										{provider.name}
									</div>
								</td>
							</tr>
						{/each}
					</tbody>
				</table>
			{/if}
		</div>

		<Dialog.Footer>
			<div class="text-xs text-muted-foreground self-center mr-auto">
				Mostrando {filteredProviders.length} registro(s)
			</div>
			{#if onClear}
				<Button variant="ghost" onclick={() => { onClear(); open = false; }}>Quitar selección</Button>
			{/if}
			<Button variant="outline" onclick={() => (open = false)}>Cancelar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
