import { setToken, handlebars } from '@opengis/fastify-table/utils.js'

import buttonEdit from './utils/buttonEdit.js';
import buttonDel from './utils/buttonDel.js';

function format(d, key, data, hash) {
    if (!key?.includes) return '';
    if (d === true) return 'Так';
    if (d === false) return 'Ні';
    if (key === 'actions') {
        return `<div class="flex items-center gap-2">${(hash.form ? buttonEdit(d, 'Редагувати') : '') + buttonDel(d)}</div>`
    }
    if (key.startsWith('{{')) {
        return handlebars.compile(key)(data);
    } else if (key.startsWith('{{') && key.includes(' ') && !(key.match(/\{\{([^\s]+)/)?.[1] in handlebars.helpers)) {
        return null;
    }
    if (!d) return '-';
    return d;
}
export default async function tableList(data, opt) {

    const { hash } = opt;
    // no data
    // const time = Date.now();
    if (hash.nodata && !data?.length) {
        const noDataText = typeof hash.nodata == 'string' ? hash.nodata : '<div class="bg-gray-200 text-center p-6 rounded-xl"><h3 class="text-lg font-semibold">Інформація відсутня</h3></div>';
        return noDataText
    }
    if (!hash.columns) return 'columns empty'
    const keys = hash.columns.split(hash.divider || ',').map(el => hash.comma ? el.trim().replace(new RegExp(hash.comma, 'g'), ',') : el.trim()).concat(hash.uid && hash.table && hash.id && !hash.noactions ? ['Дії', 'actions'] : []);

    const result = [];
    result.push('<thead class="text-left font-medium text-gray-700 dark:text-white dark:bg-transparent"> <tr>');

    // thead 
    const skip = {}
    for (let i = 0; i < keys.length; i += 2) {
        const name = keys[i];

        // check hbs 
        if (name.includes('{{')) {
            console.log(hash)
        }
        const nameHBS = name.includes('{{') ? await handlebars.compile(name)({ ...data, hash }) : false;
        // console.log(name, data, nameHBS)
        skip[name] = name.includes('{{') && !nameHBS;
        if (skip[name]) continue;

        const isActionsColumn = hash.noactions && i === keys.length - 2;
        result.push(`
            <th class="py-2 min-w-[200px] ${isActionsColumn
                ? 'last:min-w-[60px] last:max-w-[60px] last:bg-white last:sticky last:right-0'
                : ''}">
                ${nameHBS || name}
            </th>`);
    }
     result.push('</tr></thead><tbody class="divide-y divide-gray-200 dark:divide-gray-700">');

    // body 
    for (let k = 0; k < data.length; k += 1) {
        const row = data[k];
         result.push('<tr class="bg-white odd:bg-gray-50 dark:bg-transparent dark:odd:bg-transparent">');
        const obj = { form: hash.form, table: hash.table, id: row[hash.id] }
        const token = hash.table ? setToken({ ids: [JSON.stringify(obj)], uid: hash.uid, array: 1 })[0] : null;
        for (let i = 0; i < keys.length; i += 2) {

            const name = keys[i];
            const key = keys[i + 1];
            if (!key) continue;
            if (skip[name]) continue;

            const tokenData = key == 'actions' ? token : null;
            const d1 = key.includes('{{') ? await handlebars.compile(key)({ ...row, token, hash }) || '-' : null
            const isActionsColumn = hash.noactions && i === keys.length - 2;
            result.push(`
                <td class="py-2 pr-5 ${isActionsColumn ? 'last:sticky last:right-0' : ''} dark:text-white">
                    ${d1 || format(tokenData || row[key], key, row, hash)}
                </td>`);

        }
        // action token 

        result.push('</tr>');
    }
    result.push('</tbody>');

    //    console.log(Date.now() - time)
    return `<table class="min-w-full relative overflow-auto 
        divide-y-2 divide-gray-200 dark:divide-gray-700
        bg-white dark:bg-transparent 
        text-[12px] text-gray-600 dark:text-white">
        ${result.join('')}
    </table>`;
}