import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from "react";
import { twMerge } from "tailwind-merge";
import { DropdownMenu } from "./DropdownMenu";
export const DataTable = ({ columns, rows, className = "", maxRows, locale = "es-AR", isLoading = false, loadingRows = 5, rowClassName, headerClassName = "", footerClassName = "", headerCellClassName = "", footerCellClassName = "", cellClassName = "", compact = false, }) => {
    // Calcular si necesitamos scroll
    const displayRows = isLoading ? loadingRows : rows.length;
    const needsScroll = maxRows !== undefined && displayRows > maxRows;
    // Altura aproximada de una fila (px-4 py-3 = ~48px por fila, compact es menos)
    const rowHeight = compact ? 32 : 48;
    const maxHeight = maxRows ? `${maxRows * rowHeight}px` : undefined;
    const cellPadding = compact ? "px-2 py-1" : "px-4 py-3";
    // Verificar si alguna columna tiene footer
    const hasFooter = columns.some((column) => column.footer !== undefined);
    const getCellValue = (column, row) => {
        if (!column.value)
            return null;
        if (typeof column.value === "function") {
            return column.value(row);
        }
        // Si es string o number, puede ser un nombre de propiedad o un valor directo
        if (typeof column.value === "string" || typeof column.value === "number") {
            // Intentar obtener la propiedad del objeto si existe
            if (typeof column.value === "string" &&
                typeof row === "object" &&
                row !== null) {
                const value = row[column.value];
                if (value !== undefined) {
                    return value;
                }
            }
            // Si no es una propiedad, retornar el valor directo
            return column.value;
        }
        return column.value;
    };
    const formatValue = (value, type) => {
        if (React.isValidElement(value)) {
            return value;
        }
        // Convertir string a número si es necesario para currency o numeric
        let numericValue = null;
        if (typeof value === "number") {
            numericValue = value;
        }
        else if (typeof value === "string" &&
            (type === "currency" || type === "numeric")) {
            const parsed = parseFloat(value);
            if (!isNaN(parsed)) {
                numericValue = parsed;
            }
        }
        if (numericValue !== null) {
            if (type === "currency") {
                // Formatear usando el locale proporcionado sin símbolo de moneda
                const parts = new Intl.NumberFormat(locale, {
                    style: "currency",
                    currency: "EUR",
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                }).formatToParts(numericValue);
                // Construir el string sin el símbolo de moneda
                return parts
                    .filter((part) => part.type !== "currency")
                    .map((part) => part.value)
                    .join("");
            }
            if (type === "numeric") {
                // Formatear usando el locale proporcionado
                const hasDecimals = numericValue % 1 !== 0;
                return new Intl.NumberFormat(locale, {
                    minimumFractionDigits: hasDecimals ? 2 : 0,
                    maximumFractionDigits: hasDecimals ? 2 : 0,
                }).format(numericValue);
            }
        }
        if (typeof value === "string" && type === "date") {
            try {
                const date = new Date(value);
                return date.toLocaleDateString(locale);
            }
            catch {
                return value;
            }
        }
        return value;
    };
    const getAlignmentClass = (align, type) => {
        // Las columnas de tipo 'date' siempre se alinean a la izquierda
        // Las columnas de tipo 'currency' y 'numeric' siempre se alinean a la derecha
        let effectiveAlign = align;
        if (type === "date") {
            effectiveAlign = "left";
        }
        else if (type === "currency" || type === "numeric") {
            effectiveAlign = "right";
        }
        switch (effectiveAlign) {
            case "right":
                return "text-right";
            case "center":
                return "text-center";
            case "left":
            default:
                return "text-left";
        }
    };
    // Convertir array de ReactNode a array de ActionItem para DropdownMenu
    const convertActionsToOptions = (actions) => {
        return actions.map((action, index) => ({
            id: index,
            content: (_jsx("div", { onClick: (e) => {
                    // Detener la propagación para que el onClick del DropdownMenu no interfiera
                    e.stopPropagation();
                }, children: action })),
        }));
    };
    // Componente Skeleton para celdas de carga
    const SkeletonCell = () => (_jsx("div", { className: "h-4 bg-[var(--color-border-default)]/40 rounded animate-pulse w-full" }));
    return (_jsx("div", { className: `overflow-x-auto ${className}`, children: _jsx("div", { className: needsScroll ? "relative overflow-y-auto" : "", style: needsScroll && maxHeight ? { maxHeight: maxHeight } : undefined, children: _jsxs("table", { className: "w-full border-collapse font-[var(--font-default)]", children: [_jsx("thead", { className: needsScroll ? "sticky top-0 z-10" : "", children: _jsx("tr", { className: twMerge("border-b border-[var(--color-border-default)] text-[var(--color-text-primary)]", headerClassName), children: columns.map((column, index) => {
                                const headerActions = column.headerActions?.();
                                const hasHeaderActions = headerActions && headerActions.length > 0;
                                const headerBgClasses = headerClassName
                                    .split(/\s+/)
                                    .filter((cls) => cls.split(":").pop()?.startsWith("bg-"))
                                    .join(" ");
                                return (_jsx("th", { className: twMerge(cellPadding, "text-sm font-semibold", headerBgClasses || "bg-[var(--color-bg-secondary)]", getAlignmentClass(column.align, column.type), hasHeaderActions ? "relative" : "", headerCellClassName), style: {
                                        ...(column.width ? { width: column.width } : {}),
                                    }, children: isLoading ? (_jsx(SkeletonCell, {})) : hasHeaderActions ? (_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx("span", { children: column.header || "" }), _jsx(DropdownMenu, { options: convertActionsToOptions(headerActions), onOptionSelected: () => {
                                                    // Las acciones ya manejan sus propios eventos
                                                }, renderOption: (item) => item.content, replaceOnSingleOption: true })] })) : (column.header || "") }, index));
                            }) }) }), _jsx("tbody", { children: isLoading
                            ? Array.from({ length: loadingRows }).map((_, rowIndex) => (_jsx("tr", { className: "border-b border-[var(--color-border-default)] text-[var(--color-text-primary)]", children: columns.map((column, colIndex) => (_jsx("td", { className: twMerge(cellPadding, "text-sm", getAlignmentClass(column.align, column.type)), style: {
                                        ...(column.width ? { width: column.width } : {}),
                                    }, children: _jsx(SkeletonCell, {}) }, colIndex))) }, `skeleton-${rowIndex}`)))
                            : rows.map((row, rowIndex) => (_jsx("tr", { className: twMerge("group/row border-b border-[var(--color-border-default)] transition-colors hover:bg-[var(--color-bg-secondary)] text-[var(--color-text-primary)]", rowClassName?.(row)), children: columns.map((column, colIndex) => {
                                    const cellValue = getCellValue(column, row);
                                    const formattedValue = formatValue(cellValue, column.type);
                                    const tooltip = column.tooltip
                                        ? column.tooltip(row)
                                        : undefined;
                                    const rowActions = column.actions?.(row);
                                    const hasRowActions = rowActions && rowActions.length > 0;
                                    return (_jsx("td", { className: twMerge(cellPadding, "text-sm", getAlignmentClass(column.align, column.type), typeof cellClassName === "function"
                                            ? cellClassName(row, column)
                                            : cellClassName), style: {
                                            ...(column.width ? { width: column.width } : {}),
                                        }, title: tooltip
                                            ? typeof tooltip === "string"
                                                ? tooltip
                                                : undefined
                                            : undefined, children: hasRowActions ? (_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx("span", { children: formattedValue }), _jsx("div", { className: "lg:opacity-0 lg:group-hover/row:opacity-100 transition-opacity", children: _jsx(DropdownMenu, { options: convertActionsToOptions(rowActions), onOptionSelected: () => {
                                                            // Las acciones ya manejan sus propios eventos
                                                        }, renderOption: (item) => item.content, replaceOnSingleOption: true }) })] })) : (formattedValue) }, colIndex));
                                }) }, rowIndex))) }), hasFooter && (_jsx("tfoot", { className: needsScroll ? "sticky bottom-0 z-10" : "", children: _jsx("tr", { className: twMerge("border-t border-[var(--color-border-default)] text-[var(--color-text-primary)]", footerClassName), children: columns.map((column, index) => {
                                const footerBgClasses = footerClassName
                                    .split(/\s+/)
                                    .filter((cls) => cls.split(":").pop()?.startsWith("bg-"))
                                    .join(" ");
                                return (_jsx("td", { className: twMerge(cellPadding, "text-sm font-semibold", footerBgClasses || "bg-[var(--color-bg-secondary)]", getAlignmentClass(column.align, column.type), footerCellClassName), style: {
                                        ...(column.width ? { width: column.width } : {}),
                                    }, children: isLoading ? _jsx(SkeletonCell, {}) : column.footer || "" }, index));
                            }) }) }))] }) }) }));
};
