"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExportDialog = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
/**
 * ExportDialog Component
 *
 * A dialog for exporting data from a data table
 */
const react_1 = require("react");
const prop_types_1 = __importDefault(require("prop-types"));
/**
 * Formats data for export based on the selected format
 * @param {Array} data - Data to export
 * @param {Array} columns - Column definitions
 * @param {string} format - Export format (csv, json, excel)
 * @returns {string|Blob} Formatted data
 */
const formatDataForExport = (data, columns, format) => {
    if (!data || !data.length)
        return '';
    // Extract visible columns
    const visibleColumns = columns.filter(col => !col.hidden);
    switch (format) {
        case 'csv': {
            // Header row
            const header = visibleColumns.map(col => `"${col.label || col.key}"`).join(',');
            // Data rows
            const rows = data.map(row => {
                return visibleColumns
                    .map(col => {
                    const value = col.accessor ? col.accessor(row) : row[col.key];
                    // Quote strings and handle special characters
                    return typeof value === 'string' ? `"${value.replace(/"/g, '""')}"` : value;
                })
                    .join(',');
            });
            // Combine header and rows
            return [header, ...rows].join('\n');
        }
        case 'json': {
            // Format as JSON with selected columns only
            const formattedData = data.map(row => {
                const formattedRow = {};
                visibleColumns.forEach(col => {
                    formattedRow[col.key] = col.accessor ? col.accessor(row) : row[col.key];
                });
                return formattedRow;
            });
            return JSON.stringify(formattedData, null, 2);
        }
        case 'excel': {
            // For Excel, we'd typically use a library like SheetJS
            // This is a simplified example that creates a CSV with Excel-friendly formatting
            // Header row
            const header = visibleColumns.map(col => `"${col.label || col.key}"`).join(',');
            // Data rows
            const rows = data.map(row => {
                return visibleColumns
                    .map(col => {
                    const value = col.accessor ? col.accessor(row) : row[col.key];
                    // Format for Excel
                    if (typeof value === 'string')
                        return `"${value.replace(/"/g, '""')}"`;
                    if (value instanceof Date)
                        return `"${value.toISOString()}"`;
                    return value;
                })
                    .join(',');
            });
            // Combine header and rows
            return [header, ...rows].join('\n');
        }
        default:
            return '';
    }
};
/**
 * Creates a download for the formatted data
 * @param {string|Blob} data - Data to download
 * @param {string} filename - Filename
 * @param {string} format - File format
 */
const downloadData = (data, filename, format) => {
    const mimeTypes = {
        csv: 'text/csv',
        json: 'application/json',
        excel: 'application/vnd.ms-excel'
    };
    const blob = new Blob([data], { type: mimeTypes[format] || 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${filename}.${format}`;
    document.body.appendChild(a);
    a.click();
    // Clean up
    setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }, 0);
};
/**
 * ExportDialog component
 * @param {Object} props - Component props
 * @param {boolean} props.isOpen - Whether the dialog is open
 * @param {Function} props.onClose - Close handler
 * @param {Array} props.data - Data to export
 * @param {Array} props.columns - Column definitions
 * @param {string} props.filename - Filename for export (default: 'data-export')
 * @param {Array} props.formats - Available export formats (default: ['csv', 'json', 'excel'])
 * @param {string} props.defaultFormat - Default export format (default: 'csv')
 * @param {string} props.className - Additional CSS classes
 * @param {Object} props.style - Additional inline styles
 * @returns {React.ReactElement|null} ExportDialog component or null if closed
 */
const ExportDialog = ({ isOpen, onClose, data = [], columns = [], filename = 'data-export', formats = ['csv', 'json', 'excel'], defaultFormat = 'csv', className = '', style = {}, ...rest }) => {
    // State
    const [selectedFormat, setSelectedFormat] = (0, react_1.useState)(defaultFormat);
    const [exportFilename, setExportFilename] = (0, react_1.useState)(filename);
    const [selectedColumns, setSelectedColumns] = (0, react_1.useState)(columns.filter(col => !col.hidden).map(col => col.key));
    // Handle format change
    const handleFormatChange = (e) => {
        setSelectedFormat(e.target.value);
    };
    // Handle filename change
    const handleFilenameChange = (e) => {
        setExportFilename(e.target.value);
    };
    // Handle column selection change
    const handleColumnChange = (e) => {
        const { value, checked } = e.target;
        if (checked) {
            setSelectedColumns([...selectedColumns, value]);
        }
        else {
            setSelectedColumns(selectedColumns.filter(key => key !== value));
        }
    };
    // Handle select all columns
    const handleSelectAllColumns = (e) => {
        if (e.target.checked) {
            setSelectedColumns(columns.map(col => col.key));
        }
        else {
            setSelectedColumns([]);
        }
    };
    // Handle export
    const handleExport = (0, react_1.useCallback)(() => {
        // Filter columns based on selection
        const filteredColumns = columns.filter(col => selectedColumns.includes(col.key));
        // Format the data
        const formattedData = formatDataForExport(data, filteredColumns, selectedFormat);
        // Download the data
        downloadData(formattedData, exportFilename, selectedFormat);
        // Close the dialog
        onClose();
    }, [data, columns, selectedColumns, selectedFormat, exportFilename, onClose]);
    // Don't render if not open
    if (!isOpen)
        return null;
    return ((0, jsx_runtime_1.jsx)("div", { className: `bf-export-dialog ${className}`, style: style, ...rest, children: (0, jsx_runtime_1.jsxs)("div", { className: "bf-export-dialog__content", children: [(0, jsx_runtime_1.jsxs)("div", { className: "bf-export-dialog__header", children: [(0, jsx_runtime_1.jsx)("h2", { className: "bf-export-dialog__title", children: "Export Data" }), (0, jsx_runtime_1.jsx)("button", { className: "bf-export-dialog__close-button", onClick: onClose, "aria-label": "Close", children: "\u00D7" })] }), (0, jsx_runtime_1.jsxs)("div", { className: "bf-export-dialog__body", children: [(0, jsx_runtime_1.jsxs)("div", { className: "bf-export-dialog__section", children: [(0, jsx_runtime_1.jsx)("h3", { className: "bf-export-dialog__section-title", children: "Export Format" }), (0, jsx_runtime_1.jsx)("div", { className: "bf-export-dialog__format-options", children: formats.map(format => ((0, jsx_runtime_1.jsxs)("label", { className: "bf-export-dialog__format-option", children: [(0, jsx_runtime_1.jsx)("input", { type: "radio", name: "export-format", value: format, checked: selectedFormat === format, onChange: handleFormatChange }), (0, jsx_runtime_1.jsx)("span", { className: "bf-export-dialog__format-label", children: format.toUpperCase() })] }, format))) })] }), (0, jsx_runtime_1.jsxs)("div", { className: "bf-export-dialog__section", children: [(0, jsx_runtime_1.jsx)("h3", { className: "bf-export-dialog__section-title", children: "Filename" }), (0, jsx_runtime_1.jsx)("input", { type: "text", className: "bf-export-dialog__filename-input", value: exportFilename, onChange: handleFilenameChange, placeholder: "Enter filename" }), (0, jsx_runtime_1.jsxs)("span", { className: "bf-export-dialog__filename-extension", children: [".", selectedFormat] })] }), (0, jsx_runtime_1.jsxs)("div", { className: "bf-export-dialog__section", children: [(0, jsx_runtime_1.jsx)("h3", { className: "bf-export-dialog__section-title", children: "Columns to Export" }), (0, jsx_runtime_1.jsxs)("div", { className: "bf-export-dialog__column-selection", children: [(0, jsx_runtime_1.jsxs)("label", { className: "bf-export-dialog__select-all", children: [(0, jsx_runtime_1.jsx)("input", { type: "checkbox", checked: selectedColumns.length === columns.length, onChange: handleSelectAllColumns }), (0, jsx_runtime_1.jsx)("span", { children: "Select All" })] }), (0, jsx_runtime_1.jsx)("div", { className: "bf-export-dialog__column-list", children: columns.map(column => ((0, jsx_runtime_1.jsxs)("label", { className: "bf-export-dialog__column-option", children: [(0, jsx_runtime_1.jsx)("input", { type: "checkbox", value: column.key, checked: selectedColumns.includes(column.key), onChange: handleColumnChange }), (0, jsx_runtime_1.jsx)("span", { children: column.label || column.key })] }, column.key))) })] })] }), (0, jsx_runtime_1.jsxs)("div", { className: "bf-export-dialog__actions", children: [(0, jsx_runtime_1.jsx)("button", { className: "bf-export-dialog__cancel-button", onClick: onClose, children: "Cancel" }), (0, jsx_runtime_1.jsx)("button", { className: "bf-export-dialog__export-button", onClick: handleExport, disabled: !selectedColumns.length, children: "Export" })] })] })] }) }));
};
exports.ExportDialog = ExportDialog;
exports.ExportDialog.propTypes = {
    isOpen: prop_types_1.default.bool.isRequired,
    onClose: prop_types_1.default.func.isRequired,
    data: prop_types_1.default.array.isRequired,
    columns: prop_types_1.default.arrayOf(prop_types_1.default.shape({
        key: prop_types_1.default.string.isRequired,
        label: prop_types_1.default.string,
        accessor: prop_types_1.default.func,
        hidden: prop_types_1.default.bool
    })).isRequired,
    filename: prop_types_1.default.string,
    formats: prop_types_1.default.arrayOf(prop_types_1.default.string),
    defaultFormat: prop_types_1.default.string,
    className: prop_types_1.default.string,
    style: prop_types_1.default.object
};
exports.default = exports.ExportDialog;
//# sourceMappingURL=ExportDialog.js.map