import { callable, isNullish, mergeObject } from 'mixlea-utils-js';

import { mergeCellProps } from '@/components/ml-base-form';

import type { CellClickExtensionConfig } from './types';
import type { Pipeline } from '../pipeline';
import type { MlBaseFormColumn } from '@/components/ml-base-form';

export type { CellClickExtensionConfig };

export const cellClickExtensionKey = 'cellClick';

export function cellClickExtension(config?: CellClickExtensionConfig) {
  if (isNullish(config)) {
    return (pipeline: Pipeline) => pipeline;
  }

  return function (pipeline: Pipeline) {
    const mapping = config.mapping;
    const columns = pipeline.getColumns();

    pipeline.inputColumns(processColumns(columns));

    return pipeline;

    function processColumns(columns: MlBaseFormColumn[]) {
      return columns.map((col) => {
        const { getContentProps, field } = col;

        const callback = mapping[field];

        if (callback) {
          const partialColumns: Partial<MlBaseFormColumn> = {
            getContentProps: (cellValue, formData) => {
              return mergeCellProps(callable(getContentProps, cellValue, formData), {
                className: 'underline underline-offset-4 is-clickable',
                onClick: () => {
                  callback({ cellValue, formData });
                },
              });
            },
          };

          return mergeObject(col, partialColumns);
        }

        return col;
      });
    }
  };
}
