import React, { useState, useCallback } from "react";
import { Button, Box, TextField, FormControl, MenuItem } from "@mui/material";
import { UserInfo, PersonalAuthRequestBody } from "../../../services/interface";
import { personalAuthentication } from "../../../services";
import { PERSONAL_CER, 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 = PersonalAuthRequestBody;

function Personal({ userInfo }: IProps) {
  const { loading, form, submitHandler, setForm, createFieldProps } =
    useFormPage<FormValue>({
      defaultValue: {
        certificates_type: 1,
        real_name: "",
        code: "",
        id_cart: "",
      },
      submitRequest: (form) => {
        return personalAuthentication(form).then((res) => {
          message.success("提交成功");
        });
      },
      fieldProps: { required: true },
    });

  return (
    <Box
      component="form"
      sx={{
        "& .MuiFormControl-root": { mb: 3 },
      }}
      style={{ maxWidth: 500 }}
      onSubmit={submitHandler}
    >
      <TextField {...createFieldProps("real_name")} label="真实姓名" />
      <TextField
        {...createFieldProps("certificates_type")}
        label="证件类型"
        select
        onChange={(e) => {
          setForm((state) => ({
            ...state,
            certificates_type: Number(e.target.value),
          }));
        }}
      >
        {Object.values(PERSONAL_CER).map((option) => (
          <MenuItem key={option.value} value={option.value}>
            {option.cname}
          </MenuItem>
        ))}
      </TextField>
      <TextField {...createFieldProps("id_cart")} label="证件号码" />
      <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: e.target.value,
            }));
          }}
        ></ValidateCodeInput>
      </FormControl>

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

export default Personal;
