import React, { CSSProperties, useState } from "react";
import { Textarea, View } from "@tarojs/components";
import OuiLabel from "@/components/oui-label/oui-label";
import OuiSpacer from "@/components/oui-spacer/oui-spacer";
import styles from "./oui-text-area.module.scss";

class OuiTextAreaProps {
  label?: string;
  placeholder?: string | undefined;
  icon?: string;
  iconSize?: number;
  padding?: number | Array<number | string>;
  color?: string;
  radius?: number;
  cursorColor?: string;
  style?: CSSProperties;
  onInput?: Function;
  autoHeight?: boolean;
  row?: number;
  focus?: boolean;
}

function OuiTextArea({
  label,
  placeholder,
  padding = ["calc((44px - 1em) / 2)", 16],
  color = "#f5f5f5",
  radius = 16.0,
  style,
  onInput = () => {},
  autoHeight = false,
  row = 1,
  focus = false,
}: OuiTextAreaProps) {
  const [currentFocus, setCurrentFocus] = useState<boolean>(focus);

  const scannerStyle = (): CSSProperties => {
    const properties: CSSProperties = {};
    if (typeof padding === "number") {
      properties["padding"] = `${padding}px`;
    } else if (typeof padding === "object" && padding instanceof Array) {
      properties["padding"] = padding
        .map((item) => (typeof item === "number" ? `${item}px` : item))
        .join(" ");
    }
    return {
      ...properties,
      minHeight: `calc(((44px - 1em) / 2) + ${row}em)`,
      backgroundColor: color,
      borderRadius: `${radius}px`,
    };
  };

  /**
   * 值
   */
  const [value, setValue] = useState<string>("");

  const doInput = (value: string) => {
    setValue(value);
    onInput(value);
  };

  return (
    <View className={styles.component} style={style}>
      <OuiSpacer gap={4}>
        {label ? <OuiLabel>{label}</OuiLabel> : null}
        <View
          className={styles.scanner}
          style={scannerStyle()}
          onClick={() => setCurrentFocus(true)}
        >
          <Textarea
            className={styles.text}
            placeholder={placeholder}
            value={value}
            onInput={(e) => doInput(e.detail.value)}
            autoHeight={autoHeight}
            disableDefaultPadding={true}
            focus={currentFocus}
            onBlur={() => setCurrentFocus(false)}
          />
        </View>
      </OuiSpacer>
    </View>
  );
}

export default OuiTextArea;
