import React, { memo, useState } from 'react';
import { HoverWrap, Row, TD } from '../style';
import Checkbox from '../../checkbox';
import { calcOffsets, getPageInfo, mapFixedClass } from '../helpers';
import { IColumn, ITable } from '../types';

type IProps = {
    tableProps: ITable;
    rowData: any;
    state: any;
    dispatch: any;
    actionHover?: (row: any, index: number) => React.ReactNode;
};
const Rows = function({ tableProps, rowData, state, dispatch, actionHover }: IProps) {
    const { columns, showChecker, rowId, onChange, pagination = {}, dataSource = [], maxChecked = 100 } = tableProps;
    const filteredColumns = columns.filter(Boolean) as IColumn[];
    const checkFixed = filteredColumns[0] && filteredColumns[0].fixed === 'left' ? 'fix-left-cell' : '';
    const [showHover, setShowHover] = useState(filteredColumns.map(() => false));
    const { page, pageSize } = getPageInfo(state, pagination);
    const flat = state.rowChecked.reduce((acc: any, val: any) => acc.concat(val), []);
    const disableCheckAll = flat.filter(Boolean).length >= maxChecked;
    const isLocalSource = dataSource.length > pageSize;
    return rowData.map((row: any, rowIndex: number) => {
        const [leftOffset, rightOffset, leftFixedIndex, rightFixedIndex] = calcOffsets(filteredColumns, !!showChecker);

        return (
            <Row
                key={row[rowId] || rowIndex}
                onMouseEnter={
                    actionHover &&
                    function() {
                        const payload = [...filteredColumns.map(() => false)];
                        payload[rowIndex] = true;
                        setShowHover(payload);
                    }
                }
                onMouseLeave={
                    actionHover &&
                    function() {
                        setShowHover(filteredColumns.map(() => false));
                    }
                }
            >
                {[
                    !!showChecker && (
                        <TD key="checker" checker={true} align="left" className={checkFixed} offset={0}>
                            <Checkbox
                                disabled={!state.rowChecked[page - 1][rowIndex] && disableCheckAll}
                                checked={state.rowChecked[page - 1][rowIndex]}
                                onChange={checked => {
                                    const rowChecked = [...state.rowChecked];
                                    rowChecked[page - 1][rowIndex] = checked;
                                    const flat = rowChecked.reduce((acc, val) => acc.concat(val), []);
                                    dispatch({ rowChecked });
                                    onChange &&
                                        onChange({
                                            checked: dataSource
                                                .filter((row: any, index: number) =>
                                                    isLocalSource ? flat[index] : rowChecked[page - 1][index]
                                                )
                                                .map((row: any) => row[rowId]),
                                        });
                                }}
                            />
                        </TD>
                    ),
                ].concat(
                    filteredColumns.map((col: IColumn, index) => {
                        if (col.render) {
                            return (
                                <TD
                                    width={col.width}
                                    key={index}
                                    align={col.align}
                                    className={mapFixedClass(
                                        col.fixed,
                                        index === leftFixedIndex || index === rightFixedIndex
                                    )}
                                    offset={leftOffset.length > index ? leftOffset[index] : rightOffset[index]}
                                >
                                    {col.render({ value: row[col.key as string], index, row, onChange, key: col.key })}
                                    {showHover[rowIndex] && actionHover && index === filteredColumns.length - 1 && (
                                        <HoverWrap>{actionHover(row, rowIndex)}</HoverWrap>
                                    )}
                                </TD>
                            );
                        }
                        return (
                            <TD
                                align={col.align}
                                key={index}
                                width={col.width}
                                className={mapFixedClass(
                                    col.fixed,
                                    index === leftFixedIndex || index === rightFixedIndex
                                )}
                                offset={leftOffset.length > index ? leftOffset[index] : rightOffset[index]}
                            >
                                {row[col.key as string]}
                                {showHover[rowIndex] && actionHover && index === filteredColumns.length - 1 && (
                                    <HoverWrap>{actionHover(row, rowIndex)}</HoverWrap>
                                )}
                            </TD>
                        );
                    })
                )}
            </Row>
        );
    });
};
export default memo(Rows);
