import { View, Input, InputProps } from "@tarojs/components";
import style from "./index.module.less";
import { useState, useRef } from "react";
import { countCharacters, getStrByMaxLength } from "@/utils/index";
interface Props {
  placeholder?: string;
  value: string;
  disabled?: boolean;
  prefix?: () => JSX.Element | JSX.Element[] | undefined;
  suffix?: () => JSX.Element | JSX.Element[] | undefined;
  onInput: (value: string) => void;
  onBlur?: (value: string) => void;
  confirmType?: keyof InputProps.ConfirmType;
  onConfirm?: (value: string) => void;
  cursorSpacing?: number;
  extraStyle?: Record<string, string>;
  adjustPosition?: boolean
  maxlength?: number;
  placeholderStyle?: string;
}
let isInbox = false;
const index = ({
  value,
  placeholder = "请输入...",
  cursorSpacing,
  disabled,
  onInput,
  onConfirm,
  confirmType = "done",
  extraStyle,
  prefix,
  suffix,
  onBlur,
  adjustPosition,
  maxlength,
  placeholderStyle,
}: Props) => {
  const [focus, setFocus] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null); // 创建一个 ref

  const handleFocus = () => {
    isInbox = false;
    setFocus(true);
  };
  const handleBlur = () => {
    // console.log("textarea blur");
    if (!isInbox) {
      setFocus(false);
      if (onBlur && inputRef.current) {
        onBlur(inputRef.current.value);
      }
    }
  };
  const handleInput = (value: string) => {
    const len = countCharacters(value);
    if (maxlength && len > maxlength) {
      const r = getStrByMaxLength(value, maxlength);
      onInput && onInput(r);
      return;
    }
    onInput && onInput(value);
  };

  return (
    <View
      className={`${
        focus ? style.inputContainerFocused : style.inputContainer
      } p-12`}
      style={extraStyle}
    >
      <View
        className={style.inputAreaContainer}
      >
        {prefix && prefix()}
        <Input
          value={value}
          ref={inputRef}
          type="text"
          adjustPosition={adjustPosition}
          onInput={(e: any) => handleInput(e.target.value)}
          placeholder={placeholder}
          placeholderStyle={placeholderStyle ?? "color: rgba(17,17,17,.25)"}
          className={style.textInput}
          onFocus={handleFocus}
          onBlur={handleBlur}
          cursorSpacing={cursorSpacing}
          confirmType={confirmType}
          disabled={disabled}
          maxlength={10000}
          onConfirm={(e: any) => {
            onConfirm && onConfirm(e.detail.value);
          }}
        />
        {suffix && suffix()}
      </View>
    </View>
  );
};
export default index;
