import { Button, Box, InputLabel, OutlinedInput } from "@mui/material";
import { useState, useRef } from "react";
import { V_CODE_SEND_TYPE } from "../../constants";
import { sendSmsCode } from "../../services";

interface SendButtonProps {
  phone: string;
  sendType: V_CODE_SEND_TYPE;
}
function SendButton({ phone, sendType }: SendButtonProps) {
  const [loading, setLoading] = useState(false);
  const [text, setText] = useState("发送验证码");
  const timer = useRef(0);

  const looperTimer = () => {
    if (timer.current === 0) {
      setText("发送验证码");
      setLoading(false);
      return;
    }
    setTimeout(() => {
      timer.current -= 1;
      const newText = `${timer.current}s 后重新发送`;
      setText(newText);

      looperTimer();
    }, 1000);
  };

  const submitHandler = () => {
    setLoading(true);
    setText("发送中 ...");
    sendSmsCode({
      phone,
      send_type: sendType,
    })
      .then(() => {
        timer.current = 60;
        looperTimer();
      })
      .catch((e) => {
        console.log(e);
        setLoading(false);
      });
  };

  return (
    <Button
      variant="outlined"
      style={{ height: 56, marginLeft: 20 }}
      onClick={submitHandler}
      disabled={loading}
    >
      {text}
    </Button>
  );
}

interface IProps extends SendButtonProps {
  label?: string;
  name?: string;
  value: string | number;
  onChange: (
    value: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => void;
}

export default function ValidateCodeInput({
  label,
  name,
  sendType,
  value,
  phone,
  onChange,
}: IProps) {
  return (
    <Box sx={{ display: "flex", alignItems: "center" }}>
      {label && <InputLabel>{label}</InputLabel>}
      <OutlinedInput
        name={name}
        label={label}
        value={value}
        onChange={onChange}
      />
      <SendButton phone={phone} sendType={sendType} />
    </Box>
  );
}
