import React, { useState } from "react";
import { Redirect } from "react-router-dom";
import MemberPicker from "./MemberPicker";
import { Form, Col, Row, Button, InputGroup } from "react-bootstrap";
import Sender from "./Sender";

function Topup() {
  const [member, setMember] = useState(null);
  const [amount, setAmount] = useState(0);
  const [comment, setComment] = useState("");
  const [transaction, setTransaction] = useState(null);

  if (transaction !== null) {
    return <Redirect to={"/transaction/" + transaction.ID} />;
  }

  const body = () => {
    if (member === null) {
      return null;
    }
    return {
      member: member.num,
      amount: parseInt(amount) * 100,
      comment,
    };
  };

  return (
    <Sender url="/api/topup" body={body} onSuccess={setTransaction}>
      <MemberPicker member={member} onChange={setMember} />
      <Form.Group as={Row}>
        <Form.Label as="legend" column sm={2}>
          Recarga
        </Form.Label>
        <Col sm={10}>
          <InputGroup>
            <Form.Control
              type="number"
              placeholder="euros"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
            />
            <InputGroup.Append>
              <InputGroup.Text>.00 €</InputGroup.Text>
            </InputGroup.Append>
          </InputGroup>
        </Col>
      </Form.Group>
      <Form.Group as={Row}>
        <Form.Label as="legend" column sm={2}>
          Comentario
        </Form.Label>
        <Col sm={10}>
          <Form.Control
            placeholder="..."
            value={comment}
            onChange={(e) => setComment(e.target.value)}
          />
        </Col>
      </Form.Group>
      <Form.Group as={Row}>
        <Col sm={{ span: 10, offset: 2 }}>
          <Button type="submit" disabled={member === null}>
            Recarga
          </Button>
        </Col>
      </Form.Group>
    </Sender>
  );
}

export default Topup;