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

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

  React.useEffect(() => {
    if (takePhone) {
      sendSms(phone, type || "register")
        .then(() => {
          setCount(60);
          setInterval(1000);
        })
        .catch(e => {
          console.log(e);
          Toast.info(e.response.data.error);
        });
    }
  }, [takePhone]);

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

  return (
    <Div row alignItems="center" px={4} py={10}>
      <Text mr={19} textAlign="right" fontSize="sm" w={labelWidth || 80}>
        {label}
      </Text>
      <Input
        placeholder={placeholder}
        fontSize="sm"
        bg="gray100"
        flex={1}
        h={32}
        mr={10}
        value={code}
        onChangeText={value => {
          setCode(value);
          onCodeChange(value);
        }}
        borderColor="gray200"
      />
      <Button
        onPress={() => {
          sendSms(phone, type || "register")
            .then(() => {
              setCount(60);
              setInterval(1000);
            })
            .catch(e => {
              console.log(e);
              Toast.info(e.response.data.error);
            });
        }}
        appearance="ghost"
        size="tiny"
        disabled={!phone || interval}
      >
        {interval ? `已发送(${count})S` : "发送验证码"}
      </Button>
    </Div>
  );
}
