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";

interface IProps {
  userInfo?: UserInfo;
}

type FormValue = PersonalAuthRequestBody;

function Personal({ userInfo }: IProps) {
  const [loading, setLoading] = useState<boolean>(false);
  const [form, setForm] = useState<FormValue>({
    certificates_type: 1,
    real_name: "",
    code: "",
    id_cart: "",
  });
  const submitHandler = useCallback(
    (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      setLoading(true);
      personalAuthentication(form)
        .then((res) => {
          message.success("提交成功");
        })
        .finally(() => {
          setLoading(false);
        });
    },
    [form]
  );

  const createFieldProps = (name: keyof FormValue) => {
    return {
      fullWidth: true,
      name,
      value: form[name],
      onChange: (e) => {
        setForm((state) => ({ ...state, [name]: e.target.value }));
      },
    };
  };

  return (
    <Box
      component="form"
      sx={{
        "& .MuiFormControl-root": { mb: 3 },
      }}
      style={{ maxWidth: 500 }}
      onSubmit={submitHandler}
    >
      <TextField {...createFieldProps("real_name")} label="真实姓名" required />
      <TextField
        {...createFieldProps("certificates_type")}
        label="证件类型"
        required
        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="证件号码" required />
      <TextField
        label="手机号码"
        required
        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;
