import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * Table field renderer for data form
 * Dynamic rows with per-column types, subtotals, and per-row doc links
 */
import { useCallback, useMemo } from 'react';
import { LuTrash2 } from 'react-icons/lu';
import { cn } from '../../../utils/cn.js';
import { format_currency } from '../../../utils/financial_format.js';
import { DataFormFileColumn } from '../shared/data_form_file_column.js';
import { get_field_uploads } from '../../../utils/data_form_uploads.js';
import { TableReferenceAccordion } from './table_reference_accordion.js';
export function TableField(props) {
    const { field, mode, value, config, on_change, on_doc_link_click, field_uploads, on_upload_click, upload_enabled, reserve_file_column, form_data, on_field_change, reference_value_data } = props;
    const columns = field.table_columns || [];
    const rows = useMemo(() => {
        if (Array.isArray(value))
            return value;
        return [];
    }, [value]);
    const min_rows = field.table_min_rows ?? 1;
    const max_rows = field.table_max_rows ?? 50;
    // --- Resolve table styles from config ---
    const sr = config.style_resolver;
    const header_style = useMemo(() => sr.has_style('table_header') ? sr.to_style('table_header') : { backgroundColor: '#1e293b', color: '#ffffff', fontSize: '12px', fontWeight: '600' }, [sr]);
    const cell_style = useMemo(() => sr.has_style('table_cell') ? sr.to_style('table_cell') : { borderColor: '#e2e8f0', borderWidth: '1px', borderRadius: '4px' }, [sr]);
    const subtotal_style = useMemo(() => sr.has_style('table_subtotal') ? sr.to_style('table_subtotal') : { backgroundColor: '#f8fafc', fontWeight: '600', borderColor: '#d1d5db' }, [sr]);
    const add_row_style = useMemo(() => sr.has_style('table_add_row') ? sr.to_style('table_add_row') : { color: '#3b82f6', fontSize: '13px' }, [sr]);
    // Ensure minimum rows
    const effective_rows = useMemo(() => {
        if (rows.length >= min_rows)
            return rows;
        const padded = [...rows];
        while (padded.length < min_rows) {
            const empty_row = {};
            for (const col of columns) {
                empty_row[col.id] = col.default_value ?? '';
            }
            padded.push(empty_row);
        }
        return padded;
    }, [rows, min_rows, columns]);
    // Compute subtotals
    const subtotals = useMemo(() => {
        const result = {};
        for (const col of columns) {
            if (!col.subtotal)
                continue;
            let sum = 0;
            for (const row of effective_rows) {
                const val = row[col.id];
                const num = typeof val === 'number' ? val : parseFloat(String(val));
                if (!isNaN(num))
                    sum += num;
            }
            result[col.id] = sum;
        }
        return result;
    }, [columns, effective_rows]);
    const has_subtotals = Object.keys(subtotals).length > 0;
    const handle_cell_change = useCallback((row_index, col_id, cell_value) => {
        const updated = [...effective_rows];
        updated[row_index] = { ...updated[row_index], [col_id]: cell_value };
        on_change(updated);
    }, [effective_rows, on_change]);
    const handle_add_row = useCallback(() => {
        if (effective_rows.length >= max_rows)
            return;
        const new_row = {};
        for (const col of columns) {
            new_row[col.id] = col.default_value ?? '';
        }
        on_change([...effective_rows, new_row]);
    }, [effective_rows, max_rows, columns, on_change]);
    const handle_remove_row = useCallback((row_index) => {
        if (effective_rows.length <= min_rows)
            return;
        const updated = effective_rows.filter((_, i) => i !== row_index);
        on_change(updated);
    }, [effective_rows, min_rows, on_change]);
    // --- Cell input style (border from config) ---
    const cell_input_style = {
        borderColor: cell_style.borderColor || '#e2e8f0',
        borderWidth: cell_style.borderWidth || '1px',
        borderStyle: 'solid',
        borderRadius: cell_style.borderRadius || '4px',
    };
    const render_cell = (col, cell_value, row_index) => {
        if (mode === 'view') {
            return render_cell_display(col, cell_value);
        }
        const col_type = col.field_type || 'text';
        switch (col_type) {
            case 'number':
            case 'currency':
                return (_jsx("input", { type: "number", className: "cls_data_form_table_cell_input w-full text-right text-sm px-1.5 py-1", style: cell_input_style, value: cell_value != null && cell_value !== '' ? String(cell_value) : '', step: col.decimal_places != null ? Math.pow(10, -col.decimal_places) : undefined, onChange: (e) => {
                        const parsed = e.target.value === '' ? '' : parseFloat(e.target.value);
                        handle_cell_change(row_index, col.id, parsed === '' ? '' : isNaN(parsed) ? '' : parsed);
                    } }));
            case 'option':
                return (_jsxs("select", { className: "cls_data_form_table_cell_select w-full text-sm px-1.5 py-1", style: cell_input_style, value: cell_value != null ? String(cell_value) : '', onChange: (e) => handle_cell_change(row_index, col.id, e.target.value), children: [_jsx("option", { value: "", children: "Select..." }), (col.options || []).map(opt => (_jsx("option", { value: opt.value, children: opt.label }, opt.value)))] }));
            case 'boolean':
                return (_jsx("input", { type: "checkbox", className: "cls_data_form_table_cell_checkbox w-4 h-4 mx-auto block", checked: Boolean(cell_value), onChange: (e) => handle_cell_change(row_index, col.id, e.target.checked) }));
            case 'date':
                return (_jsx("input", { type: "date", className: "cls_data_form_table_cell_date w-full text-sm px-1.5 py-1", style: cell_input_style, value: cell_value != null ? String(cell_value) : '', onChange: (e) => handle_cell_change(row_index, col.id, e.target.value) }));
            default:
                return (_jsx("input", { type: "text", className: "cls_data_form_table_cell_text w-full text-sm px-1.5 py-1", style: cell_input_style, value: cell_value != null ? String(cell_value) : '', onChange: (e) => handle_cell_change(row_index, col.id, e.target.value) }));
        }
    };
    const render_cell_display = (col, cell_value) => {
        if (cell_value == null || cell_value === '')
            return _jsx("span", { className: "text-gray-300", children: "\u2014" });
        const col_type = col.field_type || 'text';
        const str_val = String(cell_value);
        switch (col_type) {
            case 'currency': {
                const num = typeof cell_value === 'number' ? cell_value : parseFloat(str_val);
                if (isNaN(num))
                    return str_val;
                const sym = col.currency_symbol || config.default_currency_symbol;
                const dec = col.decimal_places ?? config.default_decimal_places;
                return _jsx("span", { className: "text-right block", children: format_currency(num, sym, dec) });
            }
            case 'number': {
                const num = typeof cell_value === 'number' ? cell_value : parseFloat(str_val);
                if (isNaN(num))
                    return str_val;
                const dec = col.decimal_places ?? 0;
                return _jsx("span", { className: "text-right block", children: num.toFixed(dec) });
            }
            case 'boolean':
                return _jsx("span", { children: Boolean(cell_value) ? 'Yes' : 'No' });
            case 'option': {
                const opt = col.options?.find(o => o.value === str_val);
                return _jsx("span", { children: opt?.label || str_val });
            }
            default:
                return _jsx("span", { children: str_val });
        }
    };
    const variant_style = field.style_variant && config.style_resolver.has_style(field.style_variant)
        ? config.style_resolver.to_style(field.style_variant)
        : undefined;
    const has_files = Boolean((field.doc_links && field.doc_links.length > 0) ||
        (field_uploads && field_uploads.length > 0) ||
        upload_enabled);
    // Row-level uploads: stored at `${field.id}__row_${row_index}__uploads` in form_data
    const get_row_uploads = (row_index) => {
        if (!form_data)
            return [];
        return get_field_uploads(form_data, `${field.id}__row_${row_index}`);
    };
    const handle_row_upload_click = (row_index) => {
        if (on_upload_click) {
            on_upload_click();
        }
    };
    // Check if ANY row has uploads (to decide whether to show file column in table)
    const any_row_has_uploads = form_data
        ? effective_rows.some((_, i) => get_row_uploads(i).length > 0)
        : false;
    const show_row_file_col = upload_enabled || any_row_has_uploads;
    const can_add_row = mode === 'edit' && effective_rows.length < max_rows;
    const show_title_bar = Boolean(field.table_title);
    const show_file_area = has_files || reserve_file_column;
    // Border color from cell style (used on table structure)
    const border_color = cell_style.borderColor || '#e2e8f0';
    return (_jsxs("div", { className: cn('cls_data_form_table_field', 'flex flex-col gap-1 py-1'), children: [_jsxs("div", { className: "flex items-start gap-2", children: [_jsxs("div", { className: "cls_data_form_table_card flex-1 min-w-0 rounded-md overflow-hidden", style: { border: `1px solid ${border_color}` }, children: [show_title_bar && (_jsx("div", { className: "flex items-center gap-2 px-2 py-1.5", style: { borderBottom: `1px solid ${border_color}`, backgroundColor: subtotal_style.backgroundColor || '#f8fafc' }, children: field.table_title && (_jsx("div", { className: "cls_data_form_table_title text-sm font-semibold", style: variant_style, children: field.table_title })) })), _jsx("div", { className: "overflow-x-auto", children: _jsxs("table", { className: "cls_data_form_table w-full border-collapse text-sm", children: [_jsx("thead", { children: _jsxs("tr", { style: header_style, children: [columns.map((col) => (_jsxs("th", { className: cn('cls_data_form_table_th', 'text-left', (col.field_type === 'number' || col.field_type === 'currency') && 'text-right'), style: {
                                                            padding: `${header_style.paddingTop || '6px'} ${header_style.paddingRight || '8px'} ${header_style.paddingBottom || '6px'} ${header_style.paddingLeft || '8px'}`,
                                                            fontWeight: header_style.fontWeight || '600',
                                                            fontSize: header_style.fontSize || '12px',
                                                            ...(col.width ? { width: col.width } : {}),
                                                        }, children: [col.label, col.required && _jsx("span", { className: "text-red-400 ml-0.5", children: "*" })] }, col.id))), mode === 'edit' && (_jsx("th", { className: "cls_data_form_table_th_actions w-8" })), show_row_file_col && (_jsx("th", { className: "cls_data_form_table_th_files w-8" }))] }) }), _jsx("tbody", { children: effective_rows.map((row, row_index) => (_jsxs("tr", { className: cn('cls_data_form_table_row', 'hover:bg-gray-50/50'), style: { borderBottom: `1px solid ${border_color}` }, children: [columns.map((col) => (_jsx("td", { className: cn('cls_data_form_table_td', 'px-2 py-1', (col.field_type === 'number' || col.field_type === 'currency') && 'text-right'), style: { borderRight: `1px solid ${border_color}` }, children: render_cell(col, row[col.id], row_index) }, col.id))), mode === 'edit' && (_jsx("td", { className: "cls_data_form_table_td_actions px-1 py-1 text-center", children: effective_rows.length > min_rows && (_jsx("button", { type: "button", className: "text-gray-400 hover:text-red-500 transition-colors", onClick: () => handle_remove_row(row_index), title: "Remove row", children: _jsx(LuTrash2, { className: "w-3.5 h-3.5" }) })) })), show_row_file_col && (_jsx("td", { className: "cls_data_form_table_td_files px-0.5 py-1", children: _jsx(DataFormFileColumn, { field_uploads: get_row_uploads(row_index), on_upload_click: () => handle_row_upload_click(row_index), upload_enabled: upload_enabled, mode: mode, config: config }) }))] }, row_index))) }), has_subtotals && (_jsx("tfoot", { children: _jsxs("tr", { className: "cls_data_form_table_subtotal", style: {
                                                    ...subtotal_style,
                                                    borderTop: `2px solid ${subtotal_style.borderColor || '#d1d5db'}`,
                                                }, children: [columns.map((col, col_index) => (_jsx("td", { className: cn('px-2 py-1.5', (col.field_type === 'number' || col.field_type === 'currency') && 'text-right'), children: col.subtotal && subtotals[col.id] !== undefined ? (col.field_type === 'currency'
                                                            ? format_currency(subtotals[col.id], col.currency_symbol || config.default_currency_symbol, col.decimal_places ?? config.default_decimal_places)
                                                            : subtotals[col.id].toFixed(col.decimal_places ?? 0)) : col_index === 0 ? (_jsx("span", { style: { opacity: 0.6 }, children: "Total" })) : null }, col.id))), mode === 'edit' && _jsx("td", {}), show_row_file_col && _jsx("td", {})] }) }))] }) })] }), show_file_area && (has_files ? (_jsx("div", { className: "shrink-0 pt-1", children: _jsx(DataFormFileColumn, { doc_links: field.doc_links, field_uploads: field_uploads, on_doc_link_click: on_doc_link_click, on_upload_click: on_upload_click, upload_enabled: upload_enabled, mode: mode, config: config }) })) : (_jsx("div", { className: "shrink-0 ml-1", style: { width: 26 } })))] }), can_add_row && (_jsx("button", { type: "button", className: "cls_data_form_table_add_row self-start px-2 py-0.5 rounded transition-colors hover:opacity-80", style: add_row_style, onClick: handle_add_row, children: "+ Add row" })), reference_value_data && Array.isArray(reference_value_data.value) && reference_value_data.value.length > 0 && (_jsx(TableReferenceAccordion, { reference: reference_value_data, columns: columns, config: config }))] }));
}
//# sourceMappingURL=table_field.js.map