import React from 'react';
import cx from 'classnames';
import { SkeletonLoader } from '../../../skeletonLoader';
import { TableSelectionAllHeader } from './components/tableSelectionAllHeader';
import { TableSelectionCell } from './components/tableSelectionCell';
import { TableSelectionColumnText } from './components/tableSelectionColumnText';
import { TableSelectionMainCell } from './components/tableSelectionMainCell';
import { TableSelectionWrapper } from './components/tableSelectionWrapper';
import type { CellProps, InitializedTableProps, TableExtension } from '../../base/types';

const CLASS_NAME_SKELETON = 'GridTableSelectionSkeleton';

function onPropsInit<Data>(props: InitializedTableProps<Data>) {
    const [originalMainColumnDef, ...columnDefs] = props.columnDefs;

    const mainColumnDef = props.showSelectOnlyLinks
        ? {
              ...originalMainColumnDef,
              fixed: true,
              fixedOffset: 36,
              Cell: (cellProps: CellProps<Data>) => (
                  <TableSelectionMainCell
                      {...cellProps}
                      OriginalCell={originalMainColumnDef.Cell}
                  />
              ),
              LoadingIndicator: () => null,
          }
        : originalMainColumnDef;

    return {
        ...props,
        className: cx(
            props.className,
            props.highlightSelectedRows === undefined || props.highlightSelectedRows === true
                ? 'table-selection-row-highlight'
                : undefined
        ),
        columnDefs: [
            {
                maxWidth: 'min-content',
                minWidth: 'min-content',
                name: 'table-selection',
                fixed: true,
                configurable: false,

                Cell: TableSelectionCell,
                HeaderText: TableSelectionColumnText,
                LoadingIndicator: () => (
                    <SkeletonLoader
                        shape="square"
                        width={14}
                        height={14}
                        className={CLASS_NAME_SKELETON}
                    />
                ),
                HeaderLoadingIndicator: () => (
                    <SkeletonLoader
                        shape="square"
                        width={14}
                        height={14}
                        className={CLASS_NAME_SKELETON}
                    />
                ),
            },
            { ...mainColumnDef, separator: false },
            ...columnDefs,
        ],
    };
}

export const TableSelectionExtension: TableExtension = {
    name: 'selection',
    isEnabled: (props) => !!props.selectable,
    Wrapper: TableSelectionWrapper,
    onPropsInit,
    Header: TableSelectionAllHeader,
};
