import * as React from 'react';
import * as PropTypes from 'prop-types';

import classNames from '../../../utils/classnames';
import FormCell from '../formcell';
import './index.css';
import { ConfigProvider, Input } from 'tea-component';
import { usePlatform } from '../../../utils/platform';

export default function Textarea({
  // 系统属性
  id,
  className,
  style,
  events,
  // 组件属性
  label,
  labelVisible,
  defaultValue,
  placeholder,
  maxLength,
  disabled,
  focus: autoFocus,
  layout,
  requiredFlag,
  counterVisible,
  size,
}) {
  const platform = usePlatform();

  const cls = classNames({
    'weda-ui': true,
    'weda-textarea': true,
    [className]: className,
  });
  const subCls = classNames({
    'weui-cell': true,
    'weui-cell_active': true,
    'weui-cell_form': true,
    'weui-cell_disabled': disabled,
  });

  const [value, setValue] = React.useState(defaultValue);
  const [counter, setCounter] = React.useState(defaultValue?.length || 0);
  // 两次默认值不同时, 需要刷新value
  const prevDefaultValueRef = React.useRef();
  React.useEffect(() => {
    if (prevDefaultValueRef.current !== defaultValue) {
      prevDefaultValueRef.current = defaultValue;
      setValue(defaultValue);
      setCounter(defaultValue?.length || 0);
    }
  });

  const onChange = function (e) {
    const text = typeof e === 'string' ? e : e.target.value;
    setValue(text);
    setCounter(text.length || 0);
    events.change({ value: text });
  };

  let textAreaElement;
  if (platform === 'h5') {
    textAreaElement = (
      <div className={subCls}>
        <div className="weui-cell__bd">
          <textarea
            className="weui-textarea"
            placeholder={placeholder}
            value={value}
            onChange={onChange}
            maxLength={maxLength}
            disabled={disabled}
            autoFocus={autoFocus}
          ></textarea>
          {counterVisible ? (
            <div className="weui-textarea-counter">
              <span>{counter}</span>/{maxLength}
            </div>
          ) : null}
        </div>
      </div>
    );
  } else {
    textAreaElement = (
      <ConfigProvider classPrefix="wedatea2td">
        <Input.TextArea
          size={size}
          placeholder={placeholder}
          value={value}
          onChange={onChange}
          maxLength={maxLength}
          disabled={disabled}
          autoFocus={autoFocus}
          showCount
        ></Input.TextArea>
      </ConfigProvider>
    );
  }
  return (
    <FormCell
      size={size}
      id={id}
      className={cls}
      style={style}
      label={labelVisible ? label : null}
      layout={layout}
      multiCell={false}
      requiredFlag={requiredFlag}
    >
      {textAreaElement}
    </FormCell>
  );
}
