import { Button, Box, TextField, FormControl } from "@mui/material";
import {
  UserInfo,
  ForgotPasswordRequestBody,
} from "../../../services/interface";
import { forgotPassword } from "../../../services";
import { V_CODE_SEND } from "../../../constants";
import ValidateCodeInput from "../../../components/ValidateCodeInput";
import message from "../../../../../../utils/message";
import { useFormPage } from "../../../components/Form/useFormPage";

interface IProps {
  userInfo?: UserInfo;
}

type FormValue = ForgotPasswordRequestBody & { confirmPassword?: string };

export default function Password({ userInfo }: IProps) {
  const { loading, form, submitHandler, setForm, createFieldProps } =
    useFormPage<FormValue>({
      defaultValue: {
        phone: "",
        password: "",
        code: 0,
        confirmPassword: "",
      },
      submitRequest: (form) => {
        return forgotPassword(form).then((res) => {
          message.success("修改成功");
        });
      },
      fieldProps: { required: true },
    });

  return (
    <Box
      component="form"
      sx={{
        "& .MuiFormControl-root": { mb: 3 },
      }}
      style={{ maxWidth: 500 }}
      onSubmit={submitHandler}
    >
      <TextField
        label="手机号码"
        value={userInfo?.phone || ""}
        inputProps={{ readOnly: true }}
      />
      <FormControl fullWidth required>
        <ValidateCodeInput
          label="验证码"
          value={form.code || ""}
          phone={userInfo?.phone}
          sendType={V_CODE_SEND.PERSONAL_AUTH.value}
          onChange={(e) => {
            setForm((state) => ({
              ...state,
              code: Number(e.target.value),
            }));
          }}
        ></ValidateCodeInput>
      </FormControl>
      <TextField
        {...createFieldProps("password")}
        label="新密码"
        inputProps={{ type: "password", autocomplete: "new-password" }}
      />
      <TextField
        {...createFieldProps("confirmPassword")}
        label="确认新密码"
        inputProps={{ type: "password", autocomplete: "new-password" }}
      />

      <Button variant="contained" type="submit" disabled={loading}>
        确认修改
      </Button>
    </Box>
  );
}
