import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import { Div, Image, Text, Avatar, Input, Button } from 'react-native-magnus';

import { TextInputMask } from 'react-native-masked-text';
import { useTranslation } from 'react-i18next';
import { useInterval } from 'ahooks';
import { sendSms } from '../utils/SmsUtil';
import { toastInfo } from '../utils/SystemUtils';

export default function SmsInput({ phone, onCodeChange, type }) {
  const [code, setCode] = React.useState();
  const [interval, setInterval] = React.useState(null);
  const [count, setCount] = React.useState(60);
  const { t } = useTranslation();

  useInterval(
    () => {
      setCount(count - 1);
      if (count === 0) {
        setInterval(null);
      }
    },
    interval,
    { immediate: true }
  );

  return (
    <Div row alignItems="center" py={10}>
      <Text textAlign="right" w={90}>
        验证码
      </Text>
      <Div
        flex={1}
        bg="gray100"
        rounded="sm"
        px={15}
        ml={5}
        h={30}
        alignItems="stretch"
      >
        <TextInputMask
          type={'custom'}
          value={code}
          keyboardType="numeric"
          options={{
            mask: '9999',
          }}
          onChangeText={(text) => {
            setCode(text);
            onCodeChange(text);
          }}
          placeholderTextColor="#a6a6a6"
          style={{ flex: 1, fontSize: 14 }}
          placeholder={t('shu-ru-yan-zheng-ma')}
        />
      </Div>
      <Button
        onPress={() => {
          sendSms(phone, type || 'register')
            .then(() => {
              setCount(60);
              setInterval(1000);
            })
            .catch((e) => {
              console.log(e);
              toastInfo(e.error);
            });
        }}
        bg="transparent"
        color={interval ? 'gray500' : 'yellow500'}
        disabled={interval || !phone}
      >
        {interval ? `已发送(${count})S` : '发送验证码'}
      </Button>
    </Div>
  );
}
