import React, { useState, useCallback, useMemo, useEffect } from 'react';
import Input from 'antd/es/input';
import 'antd/es/input/style/index';
import { XuiTextAreaProps } from './xui-text-area.d';

const { TextArea } = Input;

const TextareaWithCount: React.FC<XuiTextAreaProps> = props => {
  const className = 'xui-ant__text-area';
  const [value, setValue] = useState<string | number | string[]>();
  const { maxLength, value: propValue, onChange } = props;
  const changeValue = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setValue(e.target.value);
    if (onChange) {
      onChange(e);
    }
  }, []);

  const tipCount = useMemo(() => {
    if (value || value === 0) {
      return String(value).length;
    }
    return 0;
  }, [value]);

  useEffect(() => {
    setValue(propValue);
  }, [propValue]);

  return (
    <div className={className}>
      <TextArea {...props} onChange={changeValue} />
      <div className={`${className}--tip`}>
        {tipCount}/{maxLength}
      </div>
    </div>
  );
};

export default TextareaWithCount;
