import { useControllableValue } from 'ahooks';
import { Col, Input, Row } from 'antd';
import Link from 'antd/lib/typography/Link';
import _ from 'lodash';
import { useCallback, useState } from 'react';
import { useIntl } from 'umi';

export interface RegularInputProps {
  value?: string;
  onChange?: (val: string) => void;
  disabled?: boolean;
  request: (val: { text: string; regular: string }) => Promise<{
    match_info: string[];
  }>;
}

const RegularInput = (props: RegularInputProps) => {
  const { request, disabled } = props;
  const [value, onChange] = useControllableValue<string>(props);
  const { formatMessage } = useIntl();
  const [checkText, setCheckText] = useState<string>('');
  const [resText, setResText] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const checkHandler = useCallback(async () => {
    try {
      setLoading(true);
      const { match_info } = await request?.({
        regular: value?.trim(),
        text: checkText?.trim(),
      });
      setResText(match_info?.join('\n') ?? '');
    } catch (e) {
      console.error('regularInput check err', e);
    } finally {
      setLoading(false);
    }
  }, [checkText, request, value]);

  return (
    <>
      <Row gutter={20}>
        <Col span={24}>
          <Input
            disabled={disabled}
            value={value}
            onChange={(e) => {
              onChange(e.target.value);
              setResText('');
            }}
            allowClear
            addonAfter={
              <Link
                disabled={_.isEmpty(value?.trim()) || _.isEmpty(checkText?.trim()) || loading}
                onClick={checkHandler}
              >
                {formatMessage({ id: '校验' })}
              </Link>
            }
            placeholder={formatMessage({ id: '正则表达式' })}
          />
        </Col>
      </Row>
      <Row gutter={20} style={{ marginTop: 20 }}>
        <Col span={12}>
          <Input.TextArea
            value={checkText}
            onChange={(e) => {
              setCheckText(e.target.value);
              setResText('');
            }}
            rows={4}
            allowClear
            placeholder={formatMessage({ id: '校验文本' })}
          />
        </Col>
        <Col span={12}>
          <Input.TextArea
            value={resText}
            rows={4}
            placeholder={formatMessage({ id: '校验结果' })}
          />
        </Col>
      </Row>
    </>
  );
};

export default RegularInput;
