import styleIndex from "./index.module.less";
import { useState, useRef } from "react";
import { countCharacters, getStrByMaxLength } from "@/utils/index";
import { View, Textarea, InputProps, type TextareaProps } from "@tarojs/components";

// 定义一个泛型接口来避免重复声明函数类型的返回值类型
type RenderFunction = () => JSX.Element | JSX.Element[] | null;

interface IProps extends Partial<Omit<TextareaProps, 'onInput' | 'onBlur' | 'onConfirm'>> {
  placeholder?: string;
  value: string;
  cursorSpacing?: number;
  maxlength?: number;
  disabled?: boolean;
  confirmType?: NonNullable<InputProps['confirmType']>; // 使用 NonNullable 防止 confirmType 被设置为 undefined
  extra?: RenderFunction;
  suffix?: RenderFunction;
  onInput?: (value: string) => void;
  onBlur?: (value: string) => void;
  bgColor?: string;
  extraClass?: string;
  className?: string;
  onConfirm?: (value: string) => void;
  placeholderStyle?: string;
}

let isInbox = false;
const index = ({
  value,
  className,
  extraClass,
  disabled,
  confirmType,
  suffix,
  placeholder = "请输入...",
  onInput,
  onBlur,
  cursorSpacing,
  maxlength,
  extra,
  onConfirm,
  placeholderStyle,
  ...rest
}: IProps) => {
  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 ? styleIndex.inputContainerFocused : styleIndex.inputContainer
      }  flex items-end px-16 py-12 min-h-52 rounded-10 bg-white`}
    >
      <View className="flex items-end flex-1 w-full">
        <View className="min-h-24 flex items-center flex-1">
          <Textarea
            ref={inputRef}
            value={value}
            disabled={disabled}
            confirmType={confirmType}
            style={{'borderRadius': '0px', maxHeight: '120px', 'lineHeight': '24px', 'height': '24px'}}
            onInput={(e: any) => handleInput(e.target.value)}
            placeholder={placeholder}
            placeholderStyle={placeholderStyle ?? 'color: rgba(17,17,17,.25)'}
            className={`${styleIndex.textInput} ${extraClass}`}
            onFocus={handleFocus}
            onBlur={handleBlur}
            autoHeight
            maxlength={10000}
            onConfirm={(e: any) => {
              onConfirm && onConfirm(e.detail.value);
            }}
            {...rest}
          />
        </View>
        {suffix && suffix()}
      </View>
    </View>
  );
};
export default index;
