import { Button, Form, Input } from "antd";
import { LockFilled } from "@ant-design/icons";
import React from "react";
import { useApolloClient } from "react-apollo";
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import Logo from "../../assets/logo240.png";
import { UPSERT_USER } from "../../graphql/user.queries";
import { emailSignInStart } from "../../redux/user/user.actions";
import {
  selectCurrentUser,
  selectSignInError
} from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
  signInError: selectSignInError
});

const mapDispatchToProps = dispatch => ({
  emailSignInStart: (email, password) =>
    dispatch(emailSignInStart({ email, password }))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(function SignInComponent({ emailSignInStart, currentUser, signInError }) {
  const apolloClient = useApolloClient();

  const handleFinish = values => {
    console.log("Login");

    const { email, password } = values;
    emailSignInStart(email, password);
    //Try to do the login using a saga here.
  };

  if (currentUser.authorized === true) {
    apolloClient
      .mutate({
        mutation: UPSERT_USER,
        variables: {
          authEmail: currentUser.email,
          authToken: currentUser.uid
        }
      })
      .then()
      .catch(error => {
        console.log("User login upsert error.", error);
      });
  }

  return (
    <div>
      {currentUser.authorized === true ? <Redirect to="/manage?" /> : null}

      <img src={Logo} height="100" width="100" alt="Bodyshop.app" />

      <Form onFinish={handleFinish}>
        <Form.Item
          name="email"
          label="E-mail"
          rules={[
            {
              //TODO Ensure using translations.
              type: "email",
              message: "Please enter a valid email."
            },
            {
              required: true,
              message: "Please your email."
            }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "Please enter your password." }]}
        >
          <Input
            prefix={<LockFilled style={{ color: "rgba(0,0,0,.25)" }} />}
            type="password"
            placeholder="Password"
          />
        </Form.Item>

        <div>Forgot password</div>
        <Button type="primary" htmlType="submit">
          Log in
        </Button>

        {signInError ? <div>{signInError.message}</div> : null}
      </Form>
    </div>
  );
});
