import * as React from 'react';
import { Row as OldRow, Col as OldCol, RowProps, ColProps } from 'antd';
import { useSize } from 'ahooks';
import { Gutter } from 'antd/lib/grid/row';

const ThemeContext = React.createContext(5);
const sizeDetails = [
  // [left, right, 列数, 间距,margin]
  [1441, Infinity, 24, 24, 24], // XXL
  [1280, 1441, 24, 16, 20], // XL
  [1024, 1280, 16, 16, 16], // LG
  [768, 1024, 12, 16, 16], // MD
  [576, 768, 8, 16, 16], // SM
  [0, 576, 4, 16, 16], // XS
];

const colSizeIndex = {
  0: 'XXL',
  1: 'XL',
  2: 'LG',
  3: 'MD',
  4: 'SM',
  5: 'XS',
};

interface ExtraProps {
  autoMode?: boolean;
  rowStyle?: React.CSSProperties;
}

interface ExtraColProps {
  colConfig?: {
    XXL?: number;
    XL?: number;
    LG?: number;
    MD?: number;
    SM?: number;
    XS?: number;
  };
}

const Row = (
  props: RowProps & React.RefAttributes<HTMLDivElement> & ExtraProps,
) => {
  const { autoMode = false, rowStyle = {}, ...restProps } = props;
  const ref = React.useRef();
  const size = useSize(ref);
  const boxSizeIndex = React.useMemo(() => {
    return (
      autoMode &&
      size &&
      sizeDetails.findIndex((item) => {
        if (size.width >= item[0] && size.width < item[1]) {
          return true;
        }
        return false;
      })
    );
  }, [size, autoMode]);

  const newGutter = React.useMemo(() => {
    const gap = sizeDetails[boxSizeIndex]?.[3];
    return [gap, gap];
  }, [boxSizeIndex]);

  const margin = React.useMemo(() => {
    const marginNum = sizeDetails[boxSizeIndex]?.[4];
    return autoMode && `0 ${marginNum}px`;
  }, [boxSizeIndex, autoMode]);

  return (
    <ThemeContext.Provider value={boxSizeIndex}>
      <div ref={ref}>
        <div style={{ margin, ...rowStyle }}>
          <OldRow gutter={newGutter as [Gutter, Gutter]} {...restProps}>
            {props.children}
          </OldRow>
        </div>
      </div>
    </ThemeContext.Provider>
  );
};

const Col = (
  props: ColProps & React.RefAttributes<HTMLDivElement> & ExtraColProps,
) => {
  const { colConfig = {} } = props;
  const boxSizeIndex = React.useContext(ThemeContext);
  const newSpan = React.useMemo(() => {
    const curColSize =
      colConfig[colSizeIndex[boxSizeIndex]] ||
      sizeDetails[boxSizeIndex]?.[2] ||
      24;
    const index = 24 / curColSize;
    const resNum = Number(props.span) * index;
    return resNum > 24 ? 24 : resNum;
  }, [boxSizeIndex, props.span]);

  return (
    <OldCol {...props} span={newSpan}>
      {props.children}
    </OldCol>
  );
};

export { Row, Col };
