import {__} from "@wordpress/i18n";
import {useMemo} from "@wordpress/element";
import Empty from "../../../../../containers/content/empty";
import Pagination from "../../../../../../../sections/pagination";
import {getFormatedDate} from "../../../../../../../../../helpers";

/**
 * Format timestamp (converts from UTC to local time)
 *
 * @param {string} timestamp Timestamp in UTC
 * @return {string}
 */
const formatTimestamp = (timestamp) => {
    if (!timestamp) {
        return __("N/A", 'limb-chatbot');
    }

    // Convert from UTC to local time and format
    return getFormatedDate(timestamp, 'YYYY-MM-DD HH:mm', true) || timestamp;
};

/**
 * Get columns from actionParameters
 *
 * @param {Array} actionParameters Action parameters
 * @return {Array}
 */
const getColumns = (actionParameters) => {
    if (!actionParameters || !Array.isArray(actionParameters) || actionParameters.length === 0) {
        return [];
    }

    // Start with timestamp column
    const columns = [
        {
            name: 'timestamp',
            label: __('Timestamp', 'limb-chatbot'),
            order: 0
        }
    ];

    // Add action parameters, sorted by order
    const sortedParameters = [...actionParameters].sort((a, b) => {
        const orderA = a.order || 0;
        const orderB = b.order || 0;
        if (orderA !== orderB) {
            return orderA - orderB;
        }
        // If order is the same, sort by id
        return (a.id || 0) - (b.id || 0);
    });

    sortedParameters.forEach(param => {
        if (param.name && param.label) {
            columns.push({
                name: param.name,
                label: param.label,
                order: param.order || 0
            });
        }
    });

    return columns;
};

/**
 * Get entry value
 *
 * @param {object} entry Entry
 * @param {string} columnName Column name (parameter name)
 * @return {string}
 */
const getEntryValue = (entry, columnName) => {
    if (columnName === 'timestamp') {
        return formatTimestamp(entry.created_at || entry.timestamp || '');
    }

    // Get value from action_data using the parameter name
    if (entry.action_data && typeof entry.action_data === 'object') {
        const value = entry.action_data[columnName];
        return value !== undefined && value !== null ? String(value) : '';
    }

    return '';
};

export default function Table({actionParameters, entries, pagination, order, loading, _callback, isDataFetched}) {
    const columns = useMemo(() => getColumns(actionParameters), [actionParameters]);

    if (!isDataFetched) {
        return null;
    }

    if (!pagination?.total || !columns.length) {
        return (
            <Empty
                title={__("No entries found", 'limb-chatbot')}
                icon="database"
            />
        );
    }

    return (
        <div className="lbaic-settings-table-container">
            <div className="lbaic-settings-table-wrapper">
                <table className="lbaic-settings-table">
                    <thead>
                    <tr>
                        {columns.map((column, index) => (
                            <th
                                key={column.name}
                                className={`lbaic-settings-table-th ${index === 0 ? 'lbaic-settings-table-th-sticky' : ''}`}
                            >
                                {column.label}
                            </th>
                        ))}
                    </tr>
                    </thead>
                    <tbody>
                    {entries.map((entry, rowIndex) => (
                        <tr
                            key={entry.id || rowIndex}
                            className={`lbaic-settings-table-tr ${rowIndex % 2 === 1 ? 'lbaic-settings-table-tr-alt' : ''}`}
                        >
                            {columns.map((column, colIndex) => {
                                const value = getEntryValue(entry, column.name);
                                return (
                                    <td
                                        key={column.name}
                                        className={`lbaic-settings-table-td ${colIndex === 0 ? 'lbaic-settings-table-td-sticky' : ''}`}
                                    >
                                        {colIndex === 0 ? (
                                            <span className="lbaic-settings-table-td-timestamp">{value}</span>
                                        ) : (
                                            <div
                                                className="lbaic-settings-table-td-content"
                                                title={value}
                                            >
                                                {value}
                                            </div>
                                        )}
                                    </td>
                                );
                            })}
                        </tr>
                    ))}
                    </tbody>
                </table>
            </div>
            {/*Pagination*/}
            {Boolean(pagination) && (
                <Pagination
                    page={pagination.page}
                    perPage={pagination.perPage}
                    total={pagination.total}
                    goTo={(page) => _callback(page, pagination.perPage)}
                    loading={loading}
                    totalItemsLabel={__("entries", 'limb-chatbot')}
                />
            )}
        </div>
    );
}