import React, { useRef, useMemo } from 'react';
import classNames from 'classnames';
import { DownOutline, TextDeletionOutline } from 'antd-mobile-icons';
import { mergeProps } from '../../utils/with-default-props';
import { shuffle } from '../../utils/shuffle';
import Popup from '../popup';
import { withNativeProps } from '../../utils/native-props';
import SafeArea from '../safe-area';
import { useMemoizedFn } from 'ahooks';
const classPrefix = 'adm-number-keyboard';
const defaultProps = {
  defaultVisible: false,
  randomOrder: false,
  showCloseButton: true,
  confirmText: null,
  closeOnConfirm: true,
  safeArea: true,
  destroyOnClose: false,
  forceRender: false
};
export const NumberKeyboard = p => {
  const props = mergeProps(defaultProps, p);
  const {
    visible,
    title,
    getContainer,
    confirmText,
    customKey,
    randomOrder,
    showCloseButton,
    onInput
  } = props;
  const keyboardRef = useRef(null);
  const keys = useMemo(() => {
    const defaultKeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
    const keyList = randomOrder ? shuffle(defaultKeys) : defaultKeys;
    const customKeys = Array.isArray(customKey) ? customKey : [customKey];
    keyList.push('0');
    if (confirmText) {
      if (customKeys.length === 2) {
        keyList.splice(9, 0, customKeys.pop());
      }
      keyList.push(customKeys[0] || '');
    } else {
      keyList.splice(9, 0, customKeys[0] || '');
      keyList.push(customKeys[1] || 'BACKSPACE');
    }
    return keyList;
  }, [customKey, confirmText, randomOrder, randomOrder && visible]);
  const timeoutRef = useRef(-1);
  const intervalRef = useRef(-1);
  const onDelete = useMemoizedFn(() => {
    var _a;
    (_a = props.onDelete) === null || _a === void 0 ? void 0 : _a.call(props);
  });
  const onBackspacePressStart = () => {
    timeoutRef.current = window.setTimeout(() => {
      onDelete();
      intervalRef.current = window.setInterval(onDelete, 150);
    }, 700);
  };
  const onBackspacePressEnd = () => {
    clearTimeout(timeoutRef.current);
    clearInterval(intervalRef.current);
  };
  const onKeyPress = (e, key) => {
    var _a, _b;
    e.preventDefault();
    switch (key) {
      case 'BACKSPACE':
        onDelete === null || onDelete === void 0 ? void 0 : onDelete();
        break;
      case 'OK':
        (_a = props.onConfirm) === null || _a === void 0 ? void 0 : _a.call(props);
        if (props.closeOnConfirm) {
          (_b = props.onClose) === null || _b === void 0 ? void 0 : _b.call(props);
        }
        break;
      default:
        // onInput should't be called when customKey doesn't exist
        if (key !== '') onInput === null || onInput === void 0 ? void 0 : onInput(key);
        break;
    }
  };
  const renderHeader = () => {
    if (!showCloseButton && !title) return null;
    return React.createElement("div", {
      className: classNames(`${classPrefix}-header`, {
        [`${classPrefix}-header-with-title`]: !!title
      })
    }, !!title && React.createElement("div", {
      className: `${classPrefix}-title`,
      "aria-label": title
    }, title), showCloseButton && React.createElement("span", {
      className: `${classPrefix}-header-close-button`,
      onClick: () => {
        var _a;
        (_a = props.onClose) === null || _a === void 0 ? void 0 : _a.call(props);
      },
      role: 'grid',
      title: 'CLOSE',
      tabIndex: -1
    }, React.createElement(DownOutline, null)));
  };
  const renderKey = (key, index) => {
    const isNumberKey = /^\d$/.test(key);
    const className = classNames(`${classPrefix}-key`, {
      [`${classPrefix}-key-number`]: isNumberKey,
      [`${classPrefix}-key-sign`]: !isNumberKey && key,
      [`${classPrefix}-key-mid`]: index === 9 && !!confirmText && keys.length < 12
    });
    const ariaProps = key ? {
      role: 'grid',
      title: key,
      tabIndex: -1
    } : undefined;
    return React.createElement("div", Object.assign({
      key: key,
      className: className,
      onTouchStart: () => {
        if (key === 'BACKSPACE') {
          onBackspacePressStart();
        }
      },
      onTouchEnd: e => {
        onKeyPress(e, key);
        if (key === 'BACKSPACE') {
          onBackspacePressEnd();
        }
      }
    }, ariaProps), key === 'BACKSPACE' ? React.createElement(TextDeletionOutline, null) : key);
  };
  return React.createElement(Popup, {
    visible: visible,
    getContainer: getContainer,
    mask: false,
    afterClose: props.afterClose,
    afterShow: props.afterShow,
    className: `${classPrefix}-popup`,
    stopPropagation: props.stopPropagation,
    destroyOnClose: props.destroyOnClose,
    forceRender: props.forceRender
  }, withNativeProps(props, React.createElement("div", {
    ref: keyboardRef,
    className: classPrefix,
    onMouseDown: e => {
      e.preventDefault();
    }
  }, renderHeader(), React.createElement("div", {
    className: `${classPrefix}-wrapper`
  }, React.createElement("div", {
    className: classNames(`${classPrefix}-main`, {
      [`${classPrefix}-main-confirmed-style`]: !!confirmText
    })
  }, keys.map(renderKey)), !!confirmText && React.createElement("div", {
    className: `${classPrefix}-confirm`
  }, React.createElement("div", {
    className: `${classPrefix}-key ${classPrefix}-key-extra ${classPrefix}-key-bs`,
    onTouchStart: () => {
      onBackspacePressStart();
    },
    onTouchEnd: e => {
      onKeyPress(e, 'BACKSPACE');
      onBackspacePressEnd();
    },
    onContextMenu: e => {
      // Long press should not trigger native context menu
      e.preventDefault();
    },
    title: 'BACKSPACE',
    role: 'grid',
    tabIndex: -1
  }, React.createElement(TextDeletionOutline, null)), React.createElement("div", {
    className: `${classPrefix}-key ${classPrefix}-key-extra ${classPrefix}-key-ok`,
    onTouchEnd: e => onKeyPress(e, 'OK'),
    role: 'grid',
    tabIndex: -1,
    "aria-label": confirmText
  }, confirmText))), props.safeArea && React.createElement("div", {
    className: `${classPrefix}-footer`
  }, React.createElement(SafeArea, {
    position: 'bottom'
  })))));
};