import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { useSearchParams } from "react-router-dom";
import dayjs, {} from "dayjs";
import { Button } from "../form-controls/Button";
import { Input } from "../form-controls/Input";
import { DateInput } from "../form-controls/DateInput";
import { AutocompleteInput } from "../form-controls/AutocompleteInput";
import { SearchSelectInput } from "../form-controls/SearchSelectInput";
import { DataField } from "./DataField";
import { normalizeIconClass } from "../utils/iconUtils";
export const Filter = (props) => {
    const { paramName, label, staticOptions, inputWidth, value: propValue, onChange, hideEmpty = false, disabled = false, } = props;
    const filterType = props.filterType || "text";
    // Calcular el ancho por defecto según el tipo de filtro
    const defaultInputWidth = filterType === "date" || filterType === "autocomplete" ? "160px" : "200px";
    const finalInputWidth = inputWidth || defaultInputWidth;
    const [searchParams, setSearchParams] = useSearchParams();
    const urlValue = paramName
        ? searchParams.get(paramName) || undefined
        : undefined;
    // Usar propValue si está presente, sino usar urlValue
    const currentValue = propValue !== undefined ? propValue : urlValue;
    const [inputValue, setInputValue] = useState(currentValue || "");
    const [searchValue, setSearchValue] = useState(currentValue || "");
    const [dateValue, setDateValue] = useState(null);
    const [autocompleteValue, setAutocompleteValue] = useState(currentValue || "");
    const [searchSelectValue, setSearchSelectValue] = useState(currentValue || undefined);
    const [searchSelectLabel, setSearchSelectLabel] = useState("");
    const [isUserTyping, setIsUserTyping] = useState(false);
    const [isOpen, setIsOpen] = useState(false);
    const [panelPosition, setPanelPosition] = useState(null);
    const containerRef = useRef(null);
    const panelRef = useRef(null);
    const inputRef = useRef(null);
    const searchInputRef = useRef(null);
    const searchSelectInputRef = useRef(null);
    const dateInputRef = useRef(null);
    const autocompleteInputRef = useRef(null);
    // Sincronizar el input con el valor actual (propValue o urlValue)
    useEffect(() => {
        if (filterType !== "autocomplete" &&
            filterType !== "search" &&
            filterType !== "searchSelect") {
            setInputValue(currentValue || "");
        }
    }, [currentValue, filterType]);
    // Sincronizar el searchValue con el valor actual (propValue o urlValue)
    useEffect(() => {
        if (filterType === "search") {
            setSearchValue(currentValue || "");
        }
    }, [currentValue, filterType]);
    // Sincronizar el searchSelectValue con el valor actual (propValue o urlValue)
    // y buscar el label si no está disponible
    useEffect(() => {
        if (filterType === "searchSelect" && currentValue) {
            const searchSelectProps = props;
            const getOptionLabel = searchSelectProps.getOptionLabel || ((item) => item.label || "");
            const getOptionValue = searchSelectProps.getOptionValue || ((item) => item.value || "");
            const onSingleSearchPromiseFn = searchSelectProps.onSingleSearchPromiseFn;
            // Si searchSelectValue es un objeto, extraer el label directamente
            if (searchSelectValue && typeof searchSelectValue === "object") {
                const label = getOptionLabel(searchSelectValue);
                const value = String(getOptionValue(searchSelectValue));
                if (value === String(currentValue)) {
                    setSearchSelectLabel(label);
                    return;
                }
            }
            // Si no tenemos el objeto completo, usar onSingleSearchPromiseFn para obtenerlo
            if (onSingleSearchPromiseFn) {
                onSingleSearchPromiseFn(currentValue)
                    .then((option) => {
                    if (option) {
                        setSearchSelectValue(option);
                        setSearchSelectLabel(getOptionLabel(option));
                    }
                    else {
                        setSearchSelectLabel(String(currentValue));
                    }
                })
                    .catch(() => {
                    setSearchSelectLabel(String(currentValue));
                });
            }
            else {
                setSearchSelectLabel(String(currentValue));
            }
        }
        else if (filterType === "searchSelect" && !currentValue) {
            setSearchSelectValue(undefined);
            setSearchSelectLabel("");
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [currentValue, filterType]);
    // Sincronizar el dateValue con el valor actual (propValue o urlValue)
    useEffect(() => {
        if (filterType === "date") {
            if (currentValue) {
                const date = dayjs(currentValue, "YYYY-MM-DD");
                setDateValue(date.isValid() ? date : null);
            }
            else {
                setDateValue(null);
            }
        }
    }, [currentValue, filterType]);
    // Sincronizar el autocompleteValue con el valor actual (propValue o urlValue)
    // Para autocomplete, mantener el value (no el label) para que AutocompleteInput pueda encontrar la opción
    useEffect(() => {
        if (filterType === "autocomplete") {
            // Mantener el value, el AutocompleteInput se encargará de mostrar el label
            setAutocompleteValue(currentValue || "");
            setIsUserTyping(false);
        }
    }, [currentValue, filterType]);
    // Cerrar el panel al hacer clic fuera
    useEffect(() => {
        if (!isOpen)
            return;
        const handleClickOutside = (event) => {
            const target = event.target;
            const isClickInsideContainer = containerRef.current?.contains(target);
            const isClickInsidePanel = panelRef.current?.contains(target);
            // Verificar si el click está dentro de un elemento con portal (DatePicker, AutocompleteInput, etc.)
            // Estos elementos tienen z-[2001] y están posicionados fixed
            let isClickInsidePortal = false;
            if (target instanceof Element) {
                let element = target;
                // Subir por el árbol DOM buscando elementos con z-index alto que sean portales
                while (element && element !== document.body) {
                    const computedStyle = window.getComputedStyle(element);
                    const zIndex = computedStyle.zIndex;
                    const position = computedStyle.position;
                    // Si encontramos un elemento fixed con z-index alto, probablemente es un portal
                    if (position === "fixed" &&
                        (zIndex === "2001" || parseInt(zIndex) >= 2001)) {
                        isClickInsidePortal = true;
                        break;
                    }
                    element = element.parentElement;
                }
            }
            if (!isClickInsideContainer &&
                !isClickInsidePanel &&
                !isClickInsidePortal) {
                setIsOpen(false);
            }
        };
        // Pequeño delay para asegurar que el portal esté montado
        const timer = setTimeout(() => {
            document.addEventListener("mousedown", handleClickOutside);
        }, 0);
        return () => {
            clearTimeout(timer);
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [isOpen]);
    // Cerrar el panel si el componente se deshabilita
    useEffect(() => {
        if (disabled) {
            setIsOpen(false);
        }
    }, [disabled]);
    const handleSetFilter = () => {
        const newValue = inputValue.trim() || undefined;
        // Si hay onChange, llamarlo con el nuevo valor
        if (onChange) {
            onChange(newValue);
        }
        // Si hay paramName, actualizar el query param
        if (paramName) {
            const newSearchParams = new URLSearchParams(searchParams);
            if (newValue) {
                newSearchParams.set(paramName, newValue);
            }
            else {
                newSearchParams.delete(paramName);
            }
            // Usar replace: true para reemplazar la URL sin agregar una nueva entrada al historial
            setSearchParams(newSearchParams, { replace: true });
        }
        setIsOpen(false);
    };
    const handleSearchChange = (e) => {
        setSearchValue(e.target.value);
    };
    const handleSearchKeyDown = (e) => {
        if (e.key === "Enter") {
            handleSearchSubmit();
        }
    };
    const handleSearchSubmit = () => {
        const newValue = searchValue.trim() || undefined;
        // Si hay onChange, llamarlo con el nuevo valor
        if (onChange) {
            onChange(newValue);
        }
        // Si hay paramName, actualizar el query param
        if (paramName) {
            const newSearchParams = new URLSearchParams(searchParams);
            if (newValue) {
                newSearchParams.set(paramName, newValue);
            }
            else {
                newSearchParams.delete(paramName);
            }
            setSearchParams(newSearchParams, { replace: true });
        }
    };
    const handleSearchIconClick = () => {
        // Verificar si el texto actual coincide con el valor actual
        const valueMatches = currentValue && searchValue.trim() === currentValue;
        if (valueMatches) {
            // Si coincide, limpiar
            const newValue = undefined;
            // Si hay onChange, llamarlo con undefined
            if (onChange) {
                onChange(newValue);
            }
            // Si hay paramName, actualizar el query param
            if (paramName) {
                const newSearchParams = new URLSearchParams(searchParams);
                newSearchParams.delete(paramName);
                setSearchParams(newSearchParams, { replace: true });
            }
            setSearchValue("");
        }
        else {
            // Si no coincide, hacer submit
            handleSearchSubmit();
        }
    };
    const handleAutocompleteChange = () => {
        // Marcar que el usuario está escribiendo para que el AutocompleteInput pueda manejar el texto libremente
        setIsUserTyping(true);
    };
    const handleAutocompleteSelect = () => {
        // Obtener el valor actual del input del AutocompleteInput
        const currentInputValue = autocompleteInputRef.current?.value || "";
        // Buscar si el texto actual coincide con alguna opción
        if (filterType === "autocomplete") {
            const autocompleteProps = props;
            const getOptionLabel = autocompleteProps.getOptionLabel || ((item) => item.label || "");
            const getOptionValue = autocompleteProps.getOptionValue || ((item) => item.value || "");
            // Buscar opción por label
            const matchingOption = autocompleteProps.options.find((opt) => getOptionLabel(opt).toLowerCase() === currentInputValue.toLowerCase());
            let newValue;
            if (matchingOption) {
                newValue = String(getOptionValue(matchingOption));
                setAutocompleteValue(newValue);
                setIsUserTyping(false);
            }
            else if (currentInputValue.trim()) {
                // Si no coincide con ninguna opción, guardar el texto tal cual
                newValue = currentInputValue.trim();
                setAutocompleteValue(newValue);
                setIsUserTyping(false);
            }
            else {
                newValue = undefined;
                setAutocompleteValue("");
                setIsUserTyping(false);
            }
            // Si hay onChange, llamarlo con el nuevo valor
            if (onChange) {
                onChange(newValue);
            }
            // Si hay paramName, actualizar el query param
            if (paramName) {
                const newSearchParams = new URLSearchParams(searchParams);
                if (newValue) {
                    newSearchParams.set(paramName, newValue);
                }
                else {
                    newSearchParams.delete(paramName);
                }
                setSearchParams(newSearchParams, { replace: true });
            }
            setIsOpen(false);
        }
    };
    const handleAutocompleteOptionSelect = (option) => {
        if (filterType === "autocomplete") {
            const autocompleteProps = props;
            const getOptionValue = autocompleteProps.getOptionValue || ((item) => item.value || "");
            const newValue = String(getOptionValue(option));
            setAutocompleteValue(newValue);
            setIsUserTyping(false);
            // Si hay onChange, llamarlo con el nuevo valor
            if (onChange) {
                onChange(newValue);
            }
            // Si hay paramName, actualizar el query param
            if (paramName) {
                const newSearchParams = new URLSearchParams(searchParams);
                newSearchParams.set(paramName, newValue);
                setSearchParams(newSearchParams, { replace: true });
            }
            setIsOpen(false);
        }
    };
    const handleSearchSelectChange = (value) => {
        if (filterType === "searchSelect") {
            const searchSelectProps = props;
            const getOptionValue = searchSelectProps.getOptionValue || ((item) => item.value || "");
            const getOptionLabel = searchSelectProps.getOptionLabel || ((item) => item.label || "");
            // Si value es un objeto, extraer el valor usando getOptionValue
            // Si value es un string/number, usarlo directamente
            let newValue;
            if (value === undefined || value === null) {
                newValue = undefined;
                setSearchSelectValue(undefined);
                setSearchSelectLabel("");
            }
            else if (typeof value === "object") {
                newValue = String(getOptionValue(value));
                setSearchSelectValue(value);
                setSearchSelectLabel(getOptionLabel(value));
            }
            else {
                newValue = String(value);
                setSearchSelectValue(value);
                // Si solo tenemos el valor, el useEffect se encargará de buscar el label
                setSearchSelectLabel("");
            }
            // Si hay onChange, llamarlo con el nuevo valor
            if (onChange) {
                onChange(newValue);
            }
            // Si hay paramName, actualizar el query param
            if (paramName) {
                const newSearchParams = new URLSearchParams(searchParams);
                if (newValue) {
                    newSearchParams.set(paramName, newValue);
                }
                else {
                    newSearchParams.delete(paramName);
                }
                setSearchParams(newSearchParams, { replace: true });
            }
            setIsOpen(false);
        }
    };
    const handleDateChange = (date) => {
        // Solo actualizar el estado temporal, no setear en la URL
        setDateValue(date);
    };
    const handleSetDateFilter = () => {
        let newValue;
        if (dateValue && dateValue.isValid()) {
            // Guardar como yyyy-mm-dd
            newValue = dateValue.format("YYYY-MM-DD");
        }
        else {
            newValue = undefined;
        }
        // Si hay onChange, llamarlo con el nuevo valor
        if (onChange) {
            onChange(newValue);
        }
        // Si hay paramName, actualizar el query param
        if (paramName) {
            const newSearchParams = new URLSearchParams(searchParams);
            if (newValue) {
                newSearchParams.set(paramName, newValue);
            }
            else {
                newSearchParams.delete(paramName);
            }
            setSearchParams(newSearchParams, { replace: true });
        }
        setIsOpen(false);
    };
    const handleStaticOptionSelect = (option) => {
        const newValue = option.value;
        // Si hay onChange, llamarlo con el nuevo valor
        if (onChange) {
            onChange(newValue);
        }
        // Si hay paramName, actualizar el query param
        if (paramName) {
            const newSearchParams = new URLSearchParams(searchParams);
            newSearchParams.set(paramName, newValue);
            setSearchParams(newSearchParams, { replace: true });
        }
        setIsOpen(false);
    };
    // Para staticOptions: mostrar el texto de la opción si el valor coincide (prioridad)
    // Para date: convertir yyyy-mm-dd a Dayjs y formatear para mostrar como dd/mm/yyyy
    // Para autocomplete: mostrar el label de la opción si el valor coincide
    const getDisplayValue = () => {
        // Primero verificar si el valor coincide con alguna opción estática
        if (staticOptions && currentValue) {
            const option = staticOptions.find((opt) => opt.value === currentValue);
            if (option) {
                return option.text;
            }
        }
        // Para autocomplete, buscar el label de la opción
        if (filterType === "autocomplete" && currentValue) {
            const autocompleteProps = props;
            if (autocompleteProps.options) {
                const getOptionLabel = autocompleteProps.getOptionLabel || ((item) => item.label || "");
                const getOptionValue = autocompleteProps.getOptionValue || ((item) => item.value || "");
                const option = autocompleteProps.options.find((opt) => String(getOptionValue(opt)) === String(currentValue));
                if (option) {
                    return getOptionLabel(option);
                }
            }
        }
        // Para searchSelect, mostrar el label guardado o buscar el label del objeto
        if (filterType === "searchSelect" && currentValue) {
            if (searchSelectLabel) {
                return searchSelectLabel;
            }
            // Si tenemos el objeto completo, extraer el label
            if (searchSelectValue && typeof searchSelectValue === "object") {
                const searchSelectProps = props;
                const getOptionLabel = searchSelectProps.getOptionLabel || ((item) => item.label || "");
                return getOptionLabel(searchSelectValue);
            }
        }
        // Si no hay opción estática que coincida, formatear según el tipo
        if (filterType === "date" && currentValue) {
            const date = dayjs(currentValue, "YYYY-MM-DD");
            if (date.isValid()) {
                return date.format("DD/MM/YYYY");
            }
        }
        return currentValue || "";
    };
    const handleClearFilter = (e) => {
        e.stopPropagation();
        // Si hay onChange, llamarlo con undefined para limpiar
        if (onChange) {
            onChange(undefined);
        }
        // Si hay paramName, actualizar el query param
        if (paramName) {
            const newSearchParams = new URLSearchParams(searchParams);
            newSearchParams.delete(paramName);
            setSearchParams(newSearchParams, { replace: true });
        }
    };
    const handleTogglePanel = () => {
        if (disabled)
            return;
        if (!isOpen) {
            // Calcular posición antes de abrir
            if (containerRef.current) {
                const rect = containerRef.current.getBoundingClientRect();
                setPanelPosition({
                    top: rect.bottom + window.scrollY + 4,
                    left: rect.left + window.scrollX,
                    width: rect.width,
                });
            }
        }
        setIsOpen(!isOpen);
    };
    // Actualizar posición cuando se abre o cuando cambia el scroll
    useEffect(() => {
        if (isOpen && containerRef.current) {
            const updatePosition = () => {
                const rect = containerRef.current?.getBoundingClientRect();
                if (rect) {
                    setPanelPosition({
                        top: rect.bottom + window.scrollY + 4,
                        left: rect.left + window.scrollX,
                        width: rect.width,
                    });
                }
            };
            updatePosition();
            window.addEventListener("scroll", updatePosition, true);
            window.addEventListener("resize", updatePosition);
            return () => {
                window.removeEventListener("scroll", updatePosition, true);
                window.removeEventListener("resize", updatePosition);
            };
        }
    }, [isOpen]);
    // Hacer foco en el input cuando se abre el panel
    useEffect(() => {
        if (isOpen) {
            // Pequeño delay para asegurar que el DOM esté actualizado
            const timer = setTimeout(() => {
                if (filterType === "text" || filterType === "number") {
                    inputRef.current?.focus();
                }
                else if (filterType === "date") {
                    dateInputRef.current?.focus();
                }
                else if (filterType === "autocomplete") {
                    autocompleteInputRef.current?.focus();
                }
                // searchSelect no necesita focus porque usa un Dialog interno
            }, 50);
            return () => clearTimeout(timer);
        }
    }, [isOpen, filterType]);
    // Si hideEmpty es true y no hay valor, no renderizar el componente
    if (hideEmpty && !currentValue) {
        return null;
    }
    // Contenedor tipo badge con diseño similar al Input
    // Altura ajustada para coincidir con input sm: py-1.5 (6px arriba y abajo) + text-sm (14px línea) = ~26px total
    const badgeContainer = (_jsxs("div", { className: "inline-flex items-center gap-2 px-3 py-1.5 h-[2.1rem] rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-default)] text-[var(--color-text-primary)] font-[var(--font-default)] cursor-pointer text-sm transition-colors", onClick: handleTogglePanel, children: [_jsx("span", { className: "text-sm min-w-[1rem]", children: getDisplayValue() || "\u00A0" }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsx("span", { className: "p-0.5 hover:bg-[var(--color-bg-secondary)] rounded transition-colors flex items-center justify-center", children: _jsx("i", { className: `${normalizeIconClass("fa-chevron-down")} text-xs text-[var(--color-text-muted)] hover:text-[var(--color-primary)] transition-all ${isOpen ? "rotate-180" : ""}` }) }), currentValue && (_jsx("button", { onClick: handleClearFilter, className: "p-0.5 hover:bg-[var(--color-bg-secondary)] rounded transition-colors flex items-center justify-center", "aria-label": "Borrar filtro", type: "button", children: _jsx("i", { className: `${normalizeIconClass("fa-times")} text-xs text-[var(--color-text-muted)] hover:text-[var(--color-primary)] transition-colors` }) }))] })] }));
    // Renderizar según el tipo de filtro
    if (filterType === "autocomplete") {
        return (_jsxs("div", { ref: containerRef, className: `relative inline-block ${disabled ? "opacity-50 pointer-events-none" : ""}`, children: [_jsx(DataField, { label: label, value: badgeContainer, className: "inline-block" }), isOpen &&
                    panelPosition &&
                    typeof document !== "undefined" &&
                    document.body &&
                    createPortal(_jsx("div", { ref: panelRef, className: "fixed z-[2001] w-fit rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-default)] shadow-[var(--shadow-lg)] p-4", style: {
                            top: `${panelPosition.top}px`,
                            left: `${panelPosition.left}px`,
                        }, children: _jsxs("div", { className: "space-y-3", children: [staticOptions && staticOptions.length > 0 && (_jsx("ul", { className: "py-1 max-h-60 overflow-auto", children: staticOptions.map((option) => (_jsx("li", { className: `px-3 py-2 cursor-pointer flex items-center gap-2 text-sm rounded transition-colors ${currentValue === option.value
                                            ? "bg-[var(--color-primary-soft)] text-[var(--color-primary)]"
                                            : "text-[var(--color-text-primary)] hover:bg-[var(--color-bg-secondary)]"}`, onMouseDown: (e) => {
                                            e.preventDefault();
                                            handleStaticOptionSelect(option);
                                        }, children: _jsx("span", { className: "font-[var(--font-default)]", children: option.text }) }, option.value))) })), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("div", { style: { width: finalInputWidth }, children: _jsx(AutocompleteInput, { ref: autocompleteInputRef, options: props.options, value: isUserTyping ? undefined : autocompleteValue, onChange: handleAutocompleteChange, getOptionLabel: props.getOptionLabel, getOptionValue: props.getOptionValue, renderOption: props.renderOption, noResultsText: props.noResultsText, onSelectOption: handleAutocompleteOptionSelect, disabled: disabled }) }), _jsx(Button, { onClick: handleAutocompleteSelect, icon: "fa-arrow-right", variant: "ghost" })] })] }) }), document.body)] }));
    }
    if (filterType === "date") {
        return (_jsxs("div", { ref: containerRef, className: `relative inline-block ${disabled ? "opacity-50 pointer-events-none" : ""}`, children: [_jsx(DataField, { label: label, value: badgeContainer, className: "inline-block" }), isOpen &&
                    panelPosition &&
                    typeof document !== "undefined" &&
                    document.body &&
                    createPortal(_jsx("div", { ref: panelRef, className: "fixed z-[2001] w-fit rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-default)] shadow-[var(--shadow-lg)] p-4", style: {
                            top: `${panelPosition.top}px`,
                            left: `${panelPosition.left}px`,
                        }, children: _jsxs("div", { className: "space-y-3", children: [staticOptions && staticOptions.length > 0 && (_jsx("ul", { className: "py-1 max-h-60 overflow-auto", children: staticOptions.map((option) => (_jsx("li", { className: `px-3 py-2 cursor-pointer flex items-center gap-2 text-sm rounded transition-colors ${currentValue === option.value
                                            ? "bg-[var(--color-primary-soft)] text-[var(--color-primary)]"
                                            : "text-[var(--color-text-primary)] hover:bg-[var(--color-bg-secondary)]"}`, onMouseDown: (e) => {
                                            e.preventDefault();
                                            handleStaticOptionSelect(option);
                                        }, children: _jsx("span", { className: "font-[var(--font-default)]", children: option.text }) }, option.value))) })), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("div", { style: { width: finalInputWidth }, children: _jsx(DateInput, { ref: dateInputRef, value: dateValue, onChange: handleDateChange, format: "dd/mm/yyyy" }) }), _jsx(Button, { onClick: handleSetDateFilter, icon: "fa-arrow-right", variant: "ghost" })] })] }) }), document.body)] }));
    }
    // Para searchSelect
    if (filterType === "searchSelect") {
        const searchSelectProps = props;
        return (_jsxs("div", { ref: containerRef, className: `relative inline-block ${disabled ? "opacity-50 pointer-events-none" : ""}`, children: [_jsx(DataField, { label: label, value: badgeContainer, className: "inline-block" }), isOpen &&
                    panelPosition &&
                    typeof document !== "undefined" &&
                    document.body &&
                    createPortal(_jsx("div", { ref: panelRef, className: "fixed z-[2001] w-fit rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-default)] shadow-[var(--shadow-lg)] p-4", style: {
                            top: `${panelPosition.top}px`,
                            left: `${panelPosition.left}px`,
                        }, children: _jsxs("div", { className: "space-y-3", children: [staticOptions && staticOptions.length > 0 && (_jsx("ul", { className: "py-1 max-h-60 overflow-auto", children: staticOptions.map((option) => (_jsx("li", { className: `px-3 py-2 cursor-pointer flex items-center gap-2 text-sm rounded transition-colors ${currentValue === option.value
                                            ? "bg-[var(--color-primary-soft)] text-[var(--color-primary)]"
                                            : "text-[var(--color-text-primary)] hover:bg-[var(--color-bg-secondary)]"}`, onMouseDown: (e) => {
                                            e.preventDefault();
                                            handleStaticOptionSelect(option);
                                        }, children: _jsx("span", { className: "font-[var(--font-default)]", children: option.text }) }, option.value))) })), _jsx("div", { style: { width: finalInputWidth }, children: _jsx(SearchSelectInput, { ref: searchSelectInputRef, value: searchSelectValue, onChange: handleSearchSelectChange, onSearchPromiseFn: searchSelectProps.onSearchPromiseFn, onSingleSearchPromiseFn: searchSelectProps.onSingleSearchPromiseFn, getOptionLabel: searchSelectProps.getOptionLabel, getOptionValue: searchSelectProps.getOptionValue, renderOption: searchSelectProps.renderOption, dialogTitle: searchSelectProps.dialogTitle, noResultsText: searchSelectProps.noResultsText }) })] }) }), document.body)] }));
    }
    // Para search
    if (filterType === "search") {
        // Mostrar X solo si hay un valor actual Y el texto del input coincide con ese valor
        const hasValue = !!currentValue;
        const valueMatches = hasValue && searchValue.trim() === currentValue;
        return (_jsx("div", { ref: containerRef, className: `relative inline-block ${disabled ? "opacity-50 pointer-events-none" : ""}`, children: _jsx(DataField, { label: label, value: _jsx("div", { style: { width: finalInputWidth }, children: _jsx(Input, { ref: searchInputRef, type: "text", value: searchValue, onChange: handleSearchChange, onKeyDown: handleSearchKeyDown, icon: valueMatches ? "fa-times" : "fa-search", iconPosition: "right", onIconClick: handleSearchIconClick, placeholder: "Buscar...", size: "sm", disabled: disabled }) }), className: "inline-block" }) }));
    }
    // Para text y number
    return (_jsxs("div", { ref: containerRef, className: `relative inline-block ${disabled ? "opacity-50 pointer-events-none" : ""}`, children: [_jsx(DataField, { label: label, value: badgeContainer, className: "inline-block" }), isOpen &&
                panelPosition &&
                typeof document !== "undefined" &&
                document.body &&
                createPortal(_jsx("div", { ref: panelRef, className: "fixed z-[2001] w-fit rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-default)] shadow-[var(--shadow-lg)] p-4", style: {
                        top: `${panelPosition.top}px`,
                        left: `${panelPosition.left}px`,
                    }, children: _jsxs("div", { className: "space-y-3", children: [staticOptions && staticOptions.length > 0 && (_jsx("ul", { className: "py-1 max-h-60 overflow-auto", children: staticOptions.map((option) => (_jsx("li", { className: `px-3 py-2 cursor-pointer flex items-center gap-2 text-sm rounded transition-colors ${urlValue === option.value
                                        ? "bg-[var(--color-primary-soft)] text-[var(--color-primary)]"
                                        : "text-[var(--color-text-primary)] hover:bg-[var(--color-bg-secondary)]"}`, onMouseDown: (e) => {
                                        e.preventDefault();
                                        handleStaticOptionSelect(option);
                                    }, children: _jsx("span", { className: "font-[var(--font-default)]", children: option.text }) }, option.value))) })), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("div", { style: { width: finalInputWidth }, children: _jsx(Input, { ref: inputRef, type: filterType === "number" ? "number" : "text", value: inputValue, onChange: (e) => setInputValue(e.target.value), placeholder: "Ingresa un valor", min: filterType === "number"
                                                ? props.min
                                                : undefined, max: filterType === "number"
                                                ? props.max
                                                : undefined, onKeyDown: (e) => {
                                                if (e.key === "Enter") {
                                                    handleSetFilter();
                                                }
                                            } }) }), _jsx(Button, { onClick: handleSetFilter, icon: "fa-arrow-right", variant: "ghost" })] })] }) }), document.body)] }));
};
