import {useState} from "@wordpress/element";
import RowDetails from "../row-details";

export default function Row({structure, row, rowIndex}) {
    const [expand, setExpand] = useState(false);

    let className = typeof structure.row?.className === 'function' ? structure.row.className(row, rowIndex) : '';
    const disabled = typeof structure.row?.disabled === 'function' ? structure.row.disabled(row, rowIndex) : Boolean(structure.row?.disabled);

    let renderDetails = false;
    if (typeof structure.row?.details?.render === 'function') {
        if (typeof structure.row.details.show === 'function') {
            renderDetails = Boolean(structure.row.details.show(row, rowIndex));
        } else {
            renderDetails = Boolean(structure.row.details.show);
        }
    }

    const handleTogglerClick = () => {
        if (renderDetails) {
            setExpand(!expand);
        } else {
            if (typeof structure.row?.togglerCallback === 'function') {
                structure.row.togglerCallback(row, rowIndex);
            }
        }
    }

    return <>
        <div className={`lbaic-settings-table-card-body-in${className ? ' ' + className : ''}`}>
            {structure.columns.map((column, columnIndex) => {
                const isNullable = typeof column.value.nullable === 'function' ? column.value.nullable(row, rowIndex) : false;
                const className = typeof column.value.className === 'function' ? column.value.className(row, columnIndex) : column.value.className;
                // Disabled column
                let disableColumn;
                if (disabled) {
                    disableColumn = structure?.disableRowColumns ? structure.disableRowColumns.includes(column.id) : true;
                }

                return <div key={column.id}
                            className={`lbaic-settings-table-card-body-item${className ? ' ' + className : ''}${disableColumn ? ' lbaic-settings-disabled' : ''}`}
                            onClick={() => !disabled && column.detailsToggler && handleTogglerClick()}>
                    {column.value.render ?
                        column.value.render(row, rowIndex)
                        :
                        <span
                            className={`lbaic-settings-table-card-body-label${isNullable ? ' lbaic-settings-table-card-body-label-null' : ''}`}
                            dangerouslySetInnerHTML={{__html: column.value.value(row, rowIndex)}}/>}
                </div>
            })}
        </div>
        {renderDetails &&
            <RowDetails key={rowIndex} show={expand}>{structure.row.details.render(row, rowIndex, expand)}</RowDetails>}
    </>
}