import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from "react";
import { Card, SearchSelectInput, Button, Input, DateInput } from "../index";
import { useForm } from "react-hook-form";
const sampleOptions = [
    {
        label: "España",
        value: "es",
        icon: "fa-flag",
        description: "Madrid",
    },
    {
        label: "Estados Unidos",
        value: "us",
        icon: "fa-flag",
        description: "Washington D.C.",
    },
    {
        label: "México",
        value: "mx",
        icon: "fa-flag",
        description: "Ciudad de México",
    },
    {
        label: "Argentina",
        value: "ar",
        icon: "fa-flag",
        description: "Buenos Aires",
    },
    {
        label: "Chile",
        value: "cl",
        icon: "fa-flag",
        description: "Santiago",
    },
    {
        label: "Colombia",
        value: "co",
        icon: "fa-flag",
        description: "Bogotá",
    },
];
const users = [
    {
        id: 1,
        firstName: "Juan",
        lastName: "Pérez",
        email: "juan.perez@empresa.com",
        role: "Desarrollador",
        department: "Tecnología",
    },
    {
        id: 2,
        firstName: "María",
        lastName: "García",
        email: "maria.garcia@empresa.com",
        role: "Diseñadora",
        department: "Diseño",
    },
    {
        id: 3,
        firstName: "Carlos",
        lastName: "Rodríguez",
        email: "carlos.rodriguez@empresa.com",
        role: "Gerente",
        department: "Ventas",
    },
    {
        id: 4,
        firstName: "Ana",
        lastName: "Martínez",
        email: "ana.martinez@empresa.com",
        role: "Analista",
        department: "Marketing",
    },
    {
        id: 5,
        firstName: "Luis",
        lastName: "Fernández",
        email: "luis.fernandez@empresa.com",
        role: "Desarrollador",
        department: "Tecnología",
    },
];
// Simular búsqueda asíncrona
const mockSearchPromise = async (text) => {
    await new Promise((resolve) => setTimeout(resolve, 500));
    const search = text.toLowerCase();
    return sampleOptions.filter((option) => option.label.toLowerCase().includes(search) ||
        (option.value && option.value.toLowerCase().includes(search)) ||
        (option.description &&
            String(option.description).toLowerCase().includes(search)));
};
// Simular búsqueda de un elemento individual por valor
const mockSingleSearchPromise = async (value) => {
    await new Promise((resolve) => setTimeout(resolve, 300));
    return sampleOptions.find((option) => option.value === value);
};
// Simular búsqueda con PaginationInterface
const mockSearchWithPagination = async (text) => {
    await new Promise((resolve) => setTimeout(resolve, 500));
    const search = text.toLowerCase();
    const filtered = sampleOptions.filter((option) => option.label.toLowerCase().includes(search) ||
        (option.value && option.value.toLowerCase().includes(search)) ||
        (option.description &&
            String(option.description).toLowerCase().includes(search)));
    return {
        list: filtered,
        limit: 10,
        page: 1,
        pages: 1,
        total: filtered.length,
    };
};
// Simular búsqueda de usuarios
const mockUserSearch = async (text) => {
    await new Promise((resolve) => setTimeout(resolve, 600));
    const search = text.toLowerCase();
    return users.filter((user) => user.firstName.toLowerCase().includes(search) ||
        user.lastName.toLowerCase().includes(search) ||
        user.email.toLowerCase().includes(search) ||
        user.role.toLowerCase().includes(search));
};
// Simular búsqueda de un usuario individual por ID
const mockSingleUserSearch = async (userId) => {
    await new Promise((resolve) => setTimeout(resolve, 300));
    return users.find((user) => user.id === userId);
};
const SearchSelectInputDocs = () => {
    const [selectedCountry, setSelectedCountry] = React.useState();
    const [internalValue, setInternalValue] = React.useState("");
    const [selectedUser, setSelectedUser] = React.useState();
    const { register, handleSubmit, reset, setFocus, formState: { errors, isSubmitted }, watch, } = useForm();
    const onSubmit = (data) => {
        console.log(data);
    };
    // Enfocar el primer campo con error después de un submit fallido
    React.useEffect(() => {
        if (isSubmitted && Object.keys(errors).length > 0) {
            // Usar setTimeout para asegurar que se ejecute después del render
            const timer = setTimeout(() => {
                if (errors.country) {
                    setFocus("country");
                }
                else if (errors.birthDate) {
                    setFocus("birthDate");
                }
                else if (errors.city) {
                    setFocus("city");
                }
            }, 100);
            return () => clearTimeout(timer);
        }
    }, [errors, isSubmitted, setFocus]);
    return (_jsx("div", { className: "max-w-5xl mx-auto space-y-8", children: _jsx(Card, { title: "SearchSelectInput - B\u00FAsqueda as\u00EDncrona y selecci\u00F3n en Dialog", children: _jsxs("div", { className: "space-y-10", children: [_jsxs("section", { children: [_jsx("h3", { className: "text-lg font-semibold mb-4", style: { color: "var(--flysoft-text-primary)" }, children: "Uso b\u00E1sico" }), _jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: [_jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "Buscar pa\u00EDs", placeholder: "Escribe y presiona Enter o click en buscar...", icon: "fa-globe", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise, onSelectOption: (option) => setSelectedCountry(option) }), _jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: "Escribe el texto, presiona Enter o haz click en el bot\u00F3n de b\u00FAsqueda para abrir el dialog con los resultados" })] }), _jsxs("div", { className: "space-y-2", children: [_jsx("p", { className: "text-sm font-medium", style: { color: "var(--flysoft-text-primary)" }, children: "Selecci\u00F3n actual" }), _jsx(Card, { variant: "outlined", children: _jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: selectedCountry
                                                        ? `${selectedCountry.label} (${selectedCountry.value?.toUpperCase() ?? "N/A"})`
                                                        : "Ningún país seleccionado" }) })] })] })] }), _jsxs("section", { children: [_jsx("h3", { className: "text-lg font-semibold mb-4", style: { color: "var(--flysoft-text-primary)" }, children: "Posici\u00F3n del bot\u00F3n de b\u00FAsqueda" }), _jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: [_jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "Bot\u00F3n a la derecha (por defecto)", placeholder: "Escribe y busca...", icon: "fa-search", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise }), _jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: "searchButtonPosition=\"right\" (valor por defecto)" })] }), _jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "Bot\u00F3n a la izquierda", placeholder: "Escribe y busca...", icon: "fa-search", iconPosition: "left", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise }), _jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: "searchButtonPosition=\"left\"" })] })] })] }), _jsxs("section", { children: [_jsx("h3", { className: "text-lg font-semibold mb-4", style: { color: "var(--flysoft-text-primary)" }, children: "Controlado vs no controlado" }), _jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: [_jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "SearchSelectInput no controlado", placeholder: "Escribe y busca...", icon: "fa-search", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise }), _jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: "sin prop value: el componente maneja internamente el valor del input" })] }), _jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "SearchSelectInput controlado", placeholder: "Escribe y busca...", icon: "fa-search", value: internalValue, getOptionValue: (option) => option.value ?? "", onChange: (val) => {
                                                    if (typeof val === "string") {
                                                        setInternalValue(val);
                                                    }
                                                }, onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise }), _jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: "con value y onChange: el valor del input se controla desde el estado externo" }), _jsx(Input, { label: "Valor actual", value: internalValue, readOnly: true, icon: "fa-code" })] })] })] }), _jsxs("section", { children: [_jsx("h3", { className: "text-lg font-semibold mb-4", style: { color: "var(--flysoft-text-primary)" }, children: "Con PaginationInterface" }), _jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "B\u00FAsqueda con paginaci\u00F3n", placeholder: "Escribe y busca pa\u00EDses...", icon: "fa-globe", onSearchPromiseFn: mockSearchWithPagination, onSingleSearchPromiseFn: mockSingleSearchPromise, dialogTitle: "Seleccione un pa\u00EDs", onSelectOption: (option) => {
                                            console.log("País seleccionado:", option);
                                        } }), _jsxs("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: ["La funci\u00F3n onSearchPromiseFn puede devolver un", " ", _jsx("code", { children: "PaginationInterface<T>" }), ". El componente extraer\u00E1 autom\u00E1ticamente el array de la propiedad", " ", _jsx("code", { children: "list" }), "."] })] })] }), _jsxs("section", { children: [_jsx("h3", { className: "text-lg font-semibold mb-4", style: { color: "var(--flysoft-text-primary)" }, children: "Personalizaci\u00F3n del Dialog" }), _jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "Dialog personalizado", placeholder: "Escribe y busca...", icon: "fa-search", dialogTitle: "Buscar y seleccionar un pa\u00EDs", noResultsText: "No se encontraron pa\u00EDses con ese criterio", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise }), _jsxs("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: ["Puedes personalizar el t\u00EDtulo del dialog con", " ", _jsx("code", { children: "dialogTitle" }), " y el mensaje de sin resultados con", " ", _jsx("code", { children: "noResultsText" }), "."] })] })] }), _jsxs("section", { children: [_jsx("h3", { className: "text-lg font-semibold mb-4", style: { color: "var(--flysoft-text-primary)" }, children: "Uso gen\u00E9rico con renderOption personalizado" }), _jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: [_jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "Buscar usuario", placeholder: "Escribe nombre, email o rol...", icon: "fa-users", onSearchPromiseFn: mockUserSearch, onSingleSearchPromiseFn: mockSingleUserSearch, getOptionLabel: (user) => `${user.firstName} ${user.lastName}`, getOptionValue: (user) => user.id, getOptionDescription: (user) => user.email, onSelectOption: (user, userId) => {
                                                    setSelectedUser(user);
                                                    console.log("Usuario seleccionado:", user, "ID:", userId);
                                                }, renderOption: (user) => (_jsxs("div", { className: "flex items-start gap-3 w-full", children: [_jsx("div", { className: "flex-shrink-0 w-10 h-10 rounded-full bg-[var(--color-primary-soft)] flex items-center justify-center", children: _jsx("i", { className: "fal fa-user text-[var(--color-primary)]" }) }), _jsxs("div", { className: "flex flex-col flex-1 min-w-0", children: [_jsxs("span", { className: "font-medium text-[var(--color-text-primary)]", children: [user.firstName, " ", user.lastName] }), _jsx("span", { className: "text-xs text-[var(--color-text-secondary)] truncate", children: user.email }), _jsxs("div", { className: "flex items-center gap-2 mt-1", children: [_jsx("span", { className: "text-xs px-2 py-0.5 rounded bg-[var(--color-bg-secondary)] text-[var(--color-text-secondary)]", children: user.role }), _jsxs("span", { className: "text-xs text-[var(--color-text-muted)]", children: ["\u2022 ", user.department] })] })] })] })) }), _jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: "usando getOptionLabel, getOptionValue y renderOption para personalizar completamente el renderizado de opciones sin propiedades label/value/description" })] }), _jsxs("div", { className: "space-y-2", children: [_jsx("p", { className: "text-sm font-medium", style: { color: "var(--flysoft-text-primary)" }, children: "Usuario seleccionado" }), _jsx(Card, { variant: "outlined", children: selectedUser ? (_jsxs("div", { className: "space-y-2", children: [_jsxs("p", { className: "text-sm font-medium", style: { color: "var(--flysoft-text-primary)" }, children: [selectedUser.firstName, " ", selectedUser.lastName] }), _jsx("p", { className: "text-xs", style: { color: "var(--flysoft-text-secondary)" }, children: selectedUser.email }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "text-xs px-2 py-0.5 rounded bg-[var(--color-bg-secondary)]", style: { color: "var(--flysoft-text-secondary)" }, children: selectedUser.role }), _jsx("span", { className: "text-xs", style: { color: "var(--flysoft-text-muted)" }, children: selectedUser.department })] }), _jsxs("p", { className: "text-xs mt-2", style: { color: "var(--flysoft-text-muted)" }, children: ["ID: ", selectedUser.id] })] })) : (_jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: "Ning\u00FAn usuario seleccionado" })) })] })] })] }), _jsxs("section", { children: [_jsx("h3", { className: "text-lg font-semibold mb-4", style: { color: "var(--flysoft-text-primary)" }, children: "Ejemplo de formulario" }), _jsx(Card, { title: "Formulario de b\u00FAsqueda con SearchSelectInput", subtitle: "Combinaci\u00F3n de SearchSelectInput, DateInput, Input y Button", children: _jsxs("form", { className: "space-y-4", onSubmit: handleSubmit(onSubmit), children: [_jsx(SearchSelectInput, { label: "Pa\u00EDs de residencia", ...register("country"), placeholder: "Busca y selecciona un pa\u00EDs", getOptionLabel: (option) => option.label, getOptionValue: (option) => option.value ?? "", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise, dialogTitle: "Seleccione un pa\u00EDs" }), _jsxs("div", { children: ["Pa\u00EDs de residencia: ", watch("country")?.toString()] }), _jsx(DateInput, { label: "Fecha de nacimiento", placeholder: "dd/mm/yyyy", ...register("birthDate") }), _jsx(Input, { label: "Ciudad", placeholder: "Introduce tu ciudad", icon: "fa-city", error: errors.city?.message }), _jsxs("div", { className: "flex justify-end gap-2", children: [_jsx(Button, { variant: "outline", icon: "fa-times", type: "submit", onClick: () => reset(), children: "Limpiar" }), _jsx(Button, { variant: "primary", icon: "fa-search", type: "submit", children: "Buscar" })] })] }) })] }), _jsxs("section", { children: [_jsx("h3", { className: "text-lg font-semibold mb-4", style: { color: "var(--flysoft-text-primary)" }, children: "Tama\u00F1os" }), _jsxs("div", { className: "space-y-4", children: [_jsx(SearchSelectInput, { label: "Tama\u00F1o peque\u00F1o", placeholder: "Escribe y busca...", size: "sm", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise }), _jsx(SearchSelectInput, { label: "Tama\u00F1o mediano (por defecto)", placeholder: "Escribe y busca...", size: "md", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise }), _jsx(SearchSelectInput, { label: "Tama\u00F1o grande", placeholder: "Escribe y busca...", size: "lg", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise })] })] }), _jsxs("section", { children: [_jsx("h3", { className: "text-lg font-semibold mb-4", style: { color: "var(--flysoft-text-primary)" }, children: "Estados y validaci\u00F3n" }), _jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: [_jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "Con error", placeholder: "Escribe y busca...", error: "Este campo es requerido", onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise }), _jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: "respeta el estado error heredado del componente Input" })] }), _jsxs("div", { className: "space-y-3", children: [_jsx(SearchSelectInput, { label: "Deshabilitado", placeholder: "No editable", icon: "fa-ban", disabled: true, onSearchPromiseFn: mockSearchPromise, onSingleSearchPromiseFn: mockSingleSearchPromise }), _jsx("p", { className: "text-sm", style: { color: "var(--flysoft-text-secondary)" }, children: "respeta el estado disabled heredado del componente Input" })] })] })] })] }) }) }));
};
export default SearchSelectInputDocs;
