import styled from "@emotion/styled";
import React, { useState } from "react";
import { useMutation } from "react-apollo";
import { RouteComponentProps, withRouter } from "react-router-dom";
import { CreateUser } from "../graphql/generated/types";
import { CREATE_USER } from "../graphql/mutations";
import { setItem } from "../storage";

type Props = {} & RouteComponentProps;

function SignUp(props: Props) {
  const [email, setEmail] = useState<string>("");
  const [name, setName] = useState<string>("");
  const [password, setPassword] = useState<string>("");

  const [createUser] = useMutation<CreateUser>(CREATE_USER);
  const signUp = async () => {
    const data = await createUser({
      variables: {
        input: {
          email,
          name,
          password,
        },
      },
    });
    const token = data!.data!.createUser!.token! || "";
    setItem("authToken", token);
    props.history.push("/");
  };

  return (
    <Container>
      <div>Together</div>
      <Input
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <Input
        placeholder="Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <Input
        placeholder="Password"
        value={password}
        type="password"
        onChange={(e) => setPassword(e.target.value)}
      />
      <button onClick={signUp}>Sign Up</button>
    </Container>
  );
}

export default withRouter(SignUp);

const Container = styled.div`
  display: flex;
  width: 100%;
  height: 100%;
  flex-direction: column;
`;

const Input = styled.input`
  -webkit-appearance: none;
  background-image: none;
  border-radius: 4px;
  color: #000000;
  padding: 10px 12px;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.18);
  font-size: 14px;
`;
