import React, { useRef, useState } from "react";
import {
  Button,
  FormControlLabel,
  FormLabel,
  Radio,
  RadioGroup,
  TextField,
} from "@material-ui/core";

import useStyles from "../../useStyles";
import { CertTypes } from "../../Contexts/CertificateContext";

const getCertTypeLabel = (certtype) => {
  if (certtype === CertTypes.Aftersales) return "Service Tool ID";
  return "VIN";
};

const CreateForm = ({ onCreate, busy }) => {
  const classes = useStyles();
  const commonnameEl = useRef(null);
  const [certType, setCertType] = useState(CertTypes.TBOX);

  const onSubmit = async (event) => {
    event.preventDefault();

    if (onCreate)
      onCreate({
        common_name: commonnameEl.current.value,
        type: certType,
      });
  };

  const onCertTypeChange = (event) => {
    setCertType(event.target.value);
  };

  return (
    <div className={classes.paper}>
      <form className={classes.form} noValidate action="{onSubmit}">
        <TextField
          id="common_name"
          name="common_name"
          label={`Common Name (${getCertTypeLabel(certType)})`}
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "17",
          }}
          required
          fullWidth
          inputRef={commonnameEl}
        />
        <FormLabel id="cert-type-group-label">Type</FormLabel>
        <RadioGroup
          row
          aria-labelledby="cert-type-group-label"
          name="cert-type"
          value={certType}
          onChange={onCertTypeChange}
          margin="normal"
        >
          <FormControlLabel
            value={CertTypes.TBOX}
            control={<Radio />}
            label="TBOX"
          />
          <FormControlLabel
            value={CertTypes.ICC}
            control={<Radio />}
            label="ICC"
          />
          <FormControlLabel
            value={CertTypes.Charging}
            control={<Radio />}
            label="Charging"
          />
        </RadioGroup>
        <Button
          type="submit"
          disabled={busy}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {busy ? "Submitting..." : "Submit"}
        </Button>
      </form>
    </div>
  );
};

export default CreateForm;
