import React, { useState } from "react";
import { TableAddon, TableProps } from "../TableProps";
import { Omit } from "../../_type";
import {
  Pagination,
  PaginationProps,
  PagingQuery,
  defaultPageSizeOptions,
} from "../../pagination/Pagination";

/**
 * `pageable` 插件用于支持表格分页
 */
export interface PageableOptions<Record = any>
  extends Omit<PaginationProps, "recordCount" | "className" | "style"> {
  /**
   * 数据总个数，用于计算页数
   * @default records.length
   */
  recordCount?: number;
}

export function pageable(options: PageableOptions = {}): TableAddon {
  return {
    getInfo: () => ({ name: "pageable" }),
    onInjectTable: render => props => {
      const { records } = props;
      const { recordCount = records.length, ...paginationProps } = options;
      return (
        <TablePagination
          tableProps={props}
          tableRender={render}
          {...paginationProps}
          recordCount={recordCount}
        />
      );
    },
  };
}

function TablePagination({
  // Table
  tableRender,
  tableProps,
  // Pagination
  recordCount,
  pageSizeOptions,
  pageIndex,
  pageSize,
  onPagingChange = () => {},
  ...props
}: PaginationProps & {
  tableProps: TableProps<any>;
  tableRender: (props: TableProps<any>) => JSX.Element;
}) {
  if (!Array.isArray(pageSizeOptions) || pageSizeOptions.length === 0) {
    pageSizeOptions = defaultPageSizeOptions; // eslint-disable-line no-param-reassign
  }

  // 为非受控组件提供状态管理
  const [internalPaging, setInternalPaging] = useState<PagingQuery>({
    pageIndex: 1,
    pageSize: pageSizeOptions[0],
  });

  // 非受控组件，使用内部状态
  if (typeof pageIndex === "undefined") {
    // eslint-disable-next-line prefer-destructuring,no-param-reassign
    pageIndex = internalPaging.pageIndex;
  }
  if (typeof pageSize === "undefined") {
    // eslint-disable-next-line prefer-destructuring,no-param-reassign
    pageSize = internalPaging.pageSize;
  }

  // 状态改变同时更新内部状态和通知外部
  // eslint-disable-next-line no-param-reassign
  onPagingChange = (onPagingChange => (query: PagingQuery) => {
    setInternalPaging(query);
    onPagingChange(query);
  })(onPagingChange);

  const { records } = tableProps;
  return (
    <>
      {tableRender({
        ...tableProps,
        records:
          records.length < recordCount
            ? records
            : records.slice((pageIndex - 1) * pageSize, pageIndex * pageSize),
      })}
      <Pagination
        {...props}
        recordCount={recordCount}
        pageSizeOptions={pageSizeOptions}
        pageIndex={pageIndex}
        pageSize={pageSize}
        onPagingChange={onPagingChange}
      />
    </>
  );
}
