'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * DataTable Editor - Configure columns and table options
 */
import { useCallback, useState } from 'react';
import { HiPlus, HiTrash, HiArrowUp, HiArrowDown, HiChevronDown, HiChevronRight } from 'react-icons/hi';
import { DATA_TABLE_FIELD_TYPES, DEFAULT_DATA_TABLE_COLUMN } from '../../types.js';
import { cn } from '../../../../utils/cn.js';
import { Switch } from '../ui/switch.js';
const FIELD_TYPE_LABELS = {
    text: 'Text',
    numeric: 'Numeric',
    dropdown: 'Dropdown',
    files: 'Files',
    checkbox: 'Checkbox',
    radiobutton: 'Radio',
    date: 'Date',
    currency: 'Currency',
    percentage: 'Percentage',
};
/**
 * User-friendly width options
 */
const WIDTH_OPTIONS = [
    { label: 'Auto', value: '', description: 'Automatic width based on content' },
    { label: 'Extra Small', value: 'w-16', description: '64px' },
    { label: 'Small', value: 'w-24', description: '96px' },
    { label: 'Medium', value: 'w-32', description: '128px' },
    { label: 'Large', value: 'w-48', description: '192px' },
    { label: 'Extra Large', value: 'w-64', description: '256px' },
    { label: 'Wide', value: 'w-80', description: '320px' },
    { label: 'Extra Wide', value: 'w-96', description: '384px' },
];
/**
 * Aggregation type options for numeric columns
 */
const AGGREGATION_OPTIONS = [
    { label: 'None', value: 'none' },
    { label: 'Sum', value: 'sum' },
    { label: 'Average', value: 'average' },
    { label: 'Count', value: 'count' },
];
export function DataTableEditor({ config, on_change, on_commit, readonly = false, }) {
    const [expanded_column, set_expanded_column] = useState(null);
    // Add column
    const handle_add_column = useCallback(() => {
        const new_column = {
            ...DEFAULT_DATA_TABLE_COLUMN,
            id: `column_${config.columns.length + 1}`,
            label: `Column ${config.columns.length + 1}`,
        };
        on_change({
            ...config,
            columns: [...config.columns, new_column],
        });
        set_expanded_column(config.columns.length);
        on_commit();
    }, [config, on_change, on_commit]);
    // Remove column
    const handle_remove_column = useCallback((index) => {
        const updated = config.columns.filter((_, i) => i !== index);
        on_change({ ...config, columns: updated });
        set_expanded_column(null);
        on_commit();
    }, [config, on_change, on_commit]);
    // Update column
    const handle_update_column = useCallback((index, updates) => {
        const updated = [...config.columns];
        updated[index] = { ...updated[index], ...updates };
        on_change({ ...config, columns: updated });
    }, [config, on_change]);
    // Move column
    const handle_move_column = useCallback((index, direction) => {
        const new_index = direction === 'up' ? index - 1 : index + 1;
        if (new_index < 0 || new_index >= config.columns.length)
            return;
        const updated = [...config.columns];
        [updated[index], updated[new_index]] = [updated[new_index], updated[index]];
        on_change({ ...config, columns: updated });
        set_expanded_column(new_index);
        on_commit();
    }, [config, on_change, on_commit]);
    // Update table option
    const handle_update_option = useCallback((key, value) => {
        on_change({ ...config, [key]: value });
    }, [config, on_change]);
    return (_jsxs("div", { className: "space-y-6", children: [_jsx("h4", { className: "text-sm font-medium", children: "Table Configuration" }), _jsxs("div", { className: "grid grid-cols-2 gap-3", children: [_jsxs("div", { className: "flex items-center justify-between p-3 border rounded-md", children: [_jsxs("div", { className: "flex-1 mr-3", children: [_jsx("label", { className: "text-sm font-medium", children: "Allow Add Row" }), _jsx("p", { className: "text-xs text-muted-foreground", children: "Users can add new rows" })] }), _jsx(Switch, { checked: config.allow_add_row ?? true, onCheckedChange: (checked) => {
                                    handle_update_option('allow_add_row', checked);
                                    on_commit();
                                }, disabled: readonly })] }), _jsxs("div", { className: "flex items-center justify-between p-3 border rounded-md", children: [_jsxs("div", { className: "flex-1 mr-3", children: [_jsx("label", { className: "text-sm font-medium", children: "Allow Delete Row" }), _jsx("p", { className: "text-xs text-muted-foreground", children: "Users can delete rows" })] }), _jsx(Switch, { checked: config.allow_delete_row ?? true, onCheckedChange: (checked) => {
                                    handle_update_option('allow_delete_row', checked);
                                    on_commit();
                                }, disabled: readonly })] }), _jsxs("div", { className: "flex items-center justify-between p-3 border rounded-md", children: [_jsxs("div", { className: "flex-1 mr-3", children: [_jsx("label", { className: "text-sm font-medium", children: "Show Row Numbers" }), _jsx("p", { className: "text-xs text-muted-foreground", children: "Display row numbers" })] }), _jsx(Switch, { checked: config.show_row_numbers ?? false, onCheckedChange: (checked) => {
                                    handle_update_option('show_row_numbers', checked);
                                    on_commit();
                                }, disabled: readonly })] }), _jsxs("div", { className: "flex items-center justify-between p-3 border rounded-md", children: [_jsxs("div", { className: "flex-1 mr-3", children: [_jsx("label", { className: "text-sm font-medium", children: "Show Subtotal Row" }), _jsx("p", { className: "text-xs text-muted-foreground", children: "Show aggregation row" })] }), _jsx(Switch, { checked: config.show_subtotal_row ?? false, onCheckedChange: (checked) => {
                                    handle_update_option('show_subtotal_row', checked);
                                    on_commit();
                                }, disabled: readonly })] })] }), _jsxs("div", { className: "flex items-center gap-4", children: [_jsx("label", { className: "text-sm font-medium whitespace-nowrap", children: "Max Rows:" }), _jsx("input", { type: "number", value: config.max_rows ?? '', onChange: (e) => handle_update_option('max_rows', e.target.value ? parseInt(e.target.value) : undefined), onBlur: on_commit, disabled: readonly, min: 1, className: cn('w-24 px-2 py-1 border rounded text-sm', 'focus:outline-none focus:ring-1 focus:ring-primary/50', readonly && 'bg-muted cursor-not-allowed'), placeholder: "No limit" })] }), _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("h5", { className: "text-sm font-medium", children: ["Columns (", config.columns.length, ")"] }), _jsxs("button", { onClick: handle_add_column, disabled: readonly, className: cn('flex items-center gap-1 px-2 py-1 text-sm rounded border hover:bg-muted', readonly && 'opacity-50 cursor-not-allowed'), children: [_jsx(HiPlus, { className: "w-4 h-4" }), "Add Column"] })] }), config.columns.length === 0 ? (_jsx("div", { className: "text-center py-4 text-muted-foreground text-sm border rounded-md bg-muted/30", children: "No columns defined. Click \"Add Column\" to create one." })) : (_jsx("div", { className: "space-y-2", children: config.columns.map((column, index) => (_jsx(ColumnEditor, { column: column, index: index, is_expanded: expanded_column === index, on_toggle: () => set_expanded_column(expanded_column === index ? null : index), on_update: (updates) => handle_update_column(index, updates), on_remove: () => handle_remove_column(index), on_move: (dir) => handle_move_column(index, dir), on_commit: on_commit, can_move_up: index > 0, can_move_down: index < config.columns.length - 1, readonly: readonly }, index))) }))] })] }));
}
function ColumnEditor({ column, index, is_expanded, on_toggle, on_update, on_remove, on_move, on_commit, can_move_up, can_move_down, readonly, }) {
    return (_jsxs("div", { className: "border rounded-md overflow-hidden", children: [_jsxs("div", { className: "flex items-center gap-2 p-2 bg-muted/30 cursor-pointer hover:bg-muted/50", onClick: on_toggle, children: [is_expanded ? (_jsx(HiChevronDown, { className: "w-4 h-4" })) : (_jsx(HiChevronRight, { className: "w-4 h-4" })), _jsx("span", { className: "flex-1 font-medium text-sm", children: column.label || `Column ${index + 1}` }), _jsx("span", { className: "text-xs text-muted-foreground px-2 py-0.5 bg-background rounded", children: FIELD_TYPE_LABELS[column.field_type] ?? column.field_type }), _jsxs("div", { className: "flex items-center gap-1", onClick: (e) => e.stopPropagation(), children: [_jsx("button", { onClick: () => on_move('up'), disabled: readonly || !can_move_up, className: "p-1 hover:bg-muted rounded disabled:opacity-30", children: _jsx(HiArrowUp, { className: "w-3 h-3" }) }), _jsx("button", { onClick: () => on_move('down'), disabled: readonly || !can_move_down, className: "p-1 hover:bg-muted rounded disabled:opacity-30", children: _jsx(HiArrowDown, { className: "w-3 h-3" }) }), _jsx("button", { onClick: on_remove, disabled: readonly, className: "p-1 text-destructive hover:bg-destructive/10 rounded disabled:opacity-50", children: _jsx(HiTrash, { className: "w-3 h-3" }) })] })] }), is_expanded && (_jsxs("div", { className: "p-3 space-y-4 bg-background", children: [_jsxs("div", { className: "grid grid-cols-2 gap-4", children: [_jsxs("div", { children: [_jsx("label", { className: "text-xs font-medium text-muted-foreground", children: "Label" }), _jsx("input", { type: "text", value: column.label, onChange: (e) => on_update({ label: e.target.value }), onBlur: on_commit, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-xs font-medium text-muted-foreground", children: "ID" }), _jsx("input", { type: "text", value: column.id, onChange: (e) => on_update({ id: e.target.value.toLowerCase().replace(/\s+/g, '_') }), onBlur: on_commit, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm font-mono" })] })] }), _jsxs("div", { children: [_jsx("label", { className: "text-xs font-medium text-muted-foreground", children: "Field Type" }), _jsx("select", { value: column.field_type, onChange: (e) => {
                                    on_update({ field_type: e.target.value });
                                    on_commit();
                                }, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm bg-background", children: DATA_TABLE_FIELD_TYPES.map((type) => (_jsx("option", { value: type, children: FIELD_TYPE_LABELS[type] }, type))) })] }), (column.field_type === 'dropdown' || column.field_type === 'radiobutton') && (_jsxs("div", { children: [_jsx("label", { className: "text-xs font-medium text-muted-foreground", children: "Options (one per line: label|value)" }), _jsx("textarea", { value: (column.options ?? []).map((o) => `${o.label}|${o.value}`).join('\n'), onChange: (e) => {
                                    const options = e.target.value.split('\n').filter(Boolean).map(line => {
                                        const [label, value] = line.split('|');
                                        return { label: label?.trim() || '', value: value?.trim() || label?.trim().toLowerCase().replace(/\s+/g, '_') || '' };
                                    });
                                    on_update({ options });
                                }, onBlur: on_commit, disabled: readonly, rows: 3, className: "w-full mt-1 px-2 py-1 border rounded text-sm font-mono", placeholder: "Yes|yes\nNo|no" })] })), _jsxs("div", { className: "grid grid-cols-2 gap-4", children: [_jsxs("div", { children: [_jsx("label", { className: "text-xs font-medium text-muted-foreground", children: "Width" }), _jsx("select", { value: column.width ?? '', onChange: (e) => {
                                            on_update({ width: e.target.value || undefined });
                                            on_commit();
                                        }, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm bg-background", children: WIDTH_OPTIONS.map((option) => (_jsxs("option", { value: option.value, children: [option.label, " ", option.description && `(${option.description})`] }, option.value))) })] }), _jsxs("div", { className: "flex items-center justify-between p-3 border rounded-md mt-5", children: [_jsx("label", { className: "text-sm", children: "Editable" }), _jsx(Switch, { checked: column.editable ?? true, onCheckedChange: (checked) => {
                                            on_update({ editable: checked });
                                            on_commit();
                                        }, disabled: readonly })] })] }), column.field_type !== 'files' && (_jsxs("div", { children: [_jsx("label", { className: "text-xs font-medium text-muted-foreground", children: "Default Value" }), column.field_type === 'checkbox' ? (_jsxs("div", { className: "flex items-center justify-between p-3 border rounded-md mt-1", children: [_jsx("span", { className: "text-sm text-muted-foreground", children: "Checked by default" }), _jsx(Switch, { checked: column.default_value === true, onCheckedChange: (checked) => {
                                            on_update({ default_value: checked });
                                            on_commit();
                                        }, disabled: readonly })] })) : column.field_type === 'dropdown' || column.field_type === 'radiobutton' ? (_jsxs("select", { value: String(column.default_value ?? ''), onChange: (e) => {
                                    on_update({ default_value: e.target.value || undefined });
                                    on_commit();
                                }, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm bg-background", children: [_jsx("option", { value: "", children: "No default" }), (column.options ?? []).map((opt) => (_jsx("option", { value: opt.value, children: opt.label }, opt.value)))] })) : (_jsx("input", { type: column.field_type === 'numeric' ? 'number' : column.field_type === 'date' ? 'date' : 'text', value: column.default_value != null ? String(column.default_value) : '', onChange: (e) => {
                                    const val = column.field_type === 'numeric'
                                        ? (e.target.value ? Number(e.target.value) : undefined)
                                        : (e.target.value || undefined);
                                    on_update({ default_value: val });
                                }, onBlur: on_commit, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm", placeholder: column.field_type === 'date' ? 'YYYY-MM-DD' : 'Enter default value' }))] })), column.field_type === 'numeric' && (_jsxs("div", { children: [_jsx("label", { className: "text-xs font-medium text-muted-foreground", children: "Aggregation (for Subtotal Row)" }), _jsx("select", { value: column.aggregation?.type ?? 'none', onChange: (e) => {
                                    const aggregationType = e.target.value;
                                    on_update({
                                        aggregation: aggregationType === 'none'
                                            ? undefined
                                            : { type: aggregationType, label: column.label }
                                    });
                                    on_commit();
                                }, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm bg-background", children: AGGREGATION_OPTIONS.map((opt) => (_jsx("option", { value: opt.value, children: opt.label }, opt.value))) }), _jsx("p", { className: "text-xs text-muted-foreground mt-1", children: "Calculate and display in the subtotal row when \"Show Subtotal Row\" is enabled" })] })), (column.field_type === 'text' || column.field_type === 'numeric') && (_jsxs("div", { className: "p-3 border rounded bg-muted/20", children: [_jsx("h6", { className: "text-xs font-medium text-muted-foreground mb-2", children: "Constraints" }), _jsxs("div", { className: "grid grid-cols-3 gap-3", children: [column.field_type === 'numeric' && (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsx("label", { className: "text-xs text-muted-foreground", children: "Min" }), _jsx("input", { type: "number", value: column.constraints?.min ?? '', onChange: (e) => on_update({
                                                            constraints: { ...column.constraints, min: e.target.value ? Number(e.target.value) : undefined }
                                                        }), onBlur: on_commit, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-xs text-muted-foreground", children: "Max" }), _jsx("input", { type: "number", value: column.constraints?.max ?? '', onChange: (e) => on_update({
                                                            constraints: { ...column.constraints, max: e.target.value ? Number(e.target.value) : undefined }
                                                        }), onBlur: on_commit, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-xs text-muted-foreground", children: "Decimals" }), _jsx("input", { type: "number", value: column.constraints?.num_decimals ?? '', onChange: (e) => on_update({
                                                            constraints: { ...column.constraints, num_decimals: e.target.value ? Number(e.target.value) : undefined }
                                                        }), onBlur: on_commit, disabled: readonly, min: 0, className: "w-full mt-1 px-2 py-1 border rounded text-sm" })] })] })), column.field_type === 'text' && (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsx("label", { className: "text-xs text-muted-foreground", children: "Max Length" }), _jsx("input", { type: "number", value: column.constraints?.length ?? '', onChange: (e) => on_update({
                                                            constraints: { ...column.constraints, length: e.target.value ? Number(e.target.value) : undefined }
                                                        }), onBlur: on_commit, disabled: readonly, min: 1, className: "w-full mt-1 px-2 py-1 border rounded text-sm" })] }), _jsxs("div", { className: "col-span-2", children: [_jsx("label", { className: "text-xs text-muted-foreground", children: "Regex" }), _jsx("input", { type: "text", value: column.constraints?.regex ?? '', onChange: (e) => on_update({
                                                            constraints: { ...column.constraints, regex: e.target.value }
                                                        }), onBlur: on_commit, disabled: readonly, className: "w-full mt-1 px-2 py-1 border rounded text-sm font-mono", placeholder: "^[A-Z]+$" })] })] })), _jsxs("div", { className: "col-span-3 flex items-center justify-between p-2 border rounded-md bg-background", children: [_jsx("label", { className: "text-sm", children: "Required" }), _jsx(Switch, { checked: column.constraints?.required ?? false, onCheckedChange: (checked) => {
                                                    on_update({ constraints: { ...column.constraints, required: checked } });
                                                    on_commit();
                                                }, disabled: readonly })] })] })] }))] }))] }));
}
//# sourceMappingURL=data_table_editor.js.map