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

	// --- PROPS Y BINDING ---
	let {
		open = $bindable(false),
		onSelect,
		onClear
	}: {
		open: boolean;
		onSelect: (client: ClientProvider) => void;
		onClear?: () => void;
	} = $props();

	// --- ESTADO LOCAL ---
	let clients = $state<ClientProvider[]>([]);
	let loading = $state(false);
	let searchTerm = $state('');
	let loaded = $state(false);

    // Filtro reactivo local
    let filteredClients = $derived(
        clients.filter(c => 
            (c.client_or_provider === 'client' || c.client_or_provider === 'both') &&
            (c.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
            c.rfc.toLowerCase().includes(searchTerm.toLowerCase()) ||
            c.id.toString().includes(searchTerm))
        )
    );

	// Efecto para cargar datos cuando se abre el modal
	$effect(() => {
		if (open && !loaded && companyStore.activeCompany?.id) {
			loadClients();
		}
	});

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

		loading = true;
		try {
			// Petición a la API - Traer todos para filtrar localmente
			const res = await clientsProvidersApi.list(companyStore.activeCompany.id, 1, 1000);

			// Normalización de respuesta
			const responseData = (res as any).data || res;

			if (responseData && responseData.items) {
				clients = responseData.items;
				loaded = true;
			} else {
				console.warn('La API no trajo items:', responseData);
			}
		} catch (e) {
			console.error('Error cargando clientes:', e);
		} finally {
			loading = false;
		}
	}

	// --- FUNCIÓN DE SELECCIÓN ---
	function handleSelect(client: ClientProvider) {
		if (onSelect) {
			onSelect(client);
		}
		open = false; // Cerrar el modal
	}
</script>

<Dialog.Root bind:open={open}>
    <Dialog.Content class="sm:max-w-[700px] max-h-[80vh] flex flex-col z-[300]">
        <Dialog.Header>
            <Dialog.Title>Seleccionar Cliente</Dialog.Title>
            <Dialog.Description>
                Busca y selecciona el cliente propietario de la parte.
            </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 filteredClients.length === 0}
                <div class="flex flex-col items-center justify-center h-48 text-muted-foreground">
                    <p>No se encontraron clientes.</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">Razón Social</th>
                            <th class="p-3 font-medium text-muted-foreground w-[100px] text-center">Estado</th>
                        </tr>
                    </thead>
                    <tbody>
                        {#each filteredClients as client}
                            <tr 
                                class="border-b hover:bg-accent/50 transition-colors cursor-pointer"
                                onclick={() => handleSelect(client)}
                            >
                                <td class="p-3 font-mono text-xs">{client.id}</td>
                                <td class="p-3 font-mono text-xs">{client.rfc}</td>
                                <td class="p-3 font-medium">
                                    <div class="flex items-center gap-2">
                                        {#if client.client_or_provider === 'client'}
                                            <User class="h-3 w-3 text-blue-500" />
                                        {:else}
                                            <Building2 class="h-3 w-3 text-purple-500" />
                                        {/if}
                                        {client.name}
                                    </div>
                                </td>
                                <td class="p-3 text-center">
                                    {#if client.is_active}
                                        <span class="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800">
                                            Activo
                                        </span>
                                    {:else}
                                        <span class="inline-flex items-center rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-800">
                                            Baja
                                        </span>
                                    {/if}
                                </td>
                            </tr>
                        {/each}
                    </tbody>
                </table>
            {/if}
        </div>

        <Dialog.Footer>
            <div class="text-xs text-muted-foreground self-center mr-auto">
                Mostrando {filteredClients.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>
