import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import { Div, Image, Text, Avatar, Input, Button } from 'react-native-magnus';
import { Toast } from '@ant-design/react-native';
import { useInterval } from 'ahooks';
import { sendSms } from '../Utils/SmsUtil';

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

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

  return (
    <Div
      row
      alignItems="center"
      ml={15}
      py={10}
      borderBottomWidth={1}
      borderBottomColor="gray100"
    >
      <Text textAlign="left" fontSize="lg" mr={12} w={labelWidth || 80}>
        验证码
      </Text>
      <Input
        placeholder="输入验证码"
        fontSize="lg"
        // bg="gray100"
        flex={1}
        h={32}
        mr={10}
        value={code}
        borderWidth={0}
        onChangeText={(value) => {
          setCode(value);
          onCodeChange(value);
        }}
      />
      <Button
        bg="transparent"
        color={interval ? 'gray500' : 'brand500'}
        fontSize="sm"
        disabled={!phone || interval}
        onPress={() => {
          sendSms(phone, type || 'register')
            .then(() => {
              setCount(60);
              setInterval(1000);
            })
            .catch((e) => {
              console.log(e);
              Toast.info(e.response.data.error);
            });
        }}
      >
        {interval ? `已发送(${count})S` : '发送验证码'}
      </Button>
    </Div>
  );
}
