import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Alert, Button, Form, Input, Typography } from "antd";
import React from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import ImEXOnlineLogo from "../../../assets/logo192.png";
import { emailSignInStart } from "../../../redux/user/user.actions";
import { sendPasswordReset } from "../../../redux/user/user.actions";
import {
  selectLoginLoading,
  selectPasswordReset,
  selectSignInError,
} from "../../../redux/user/user.selectors";
import "./sign-in.page.styles.scss";

const mapStateToProps = createStructuredSelector({
  signInError: selectSignInError,
  loginLoading: selectLoginLoading,
  passwordReset: selectPasswordReset,
});

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

export function SignInPage({
  emailSignInStart,
  signInError,
  loginLoading,
  sendPasswordReset,
  passwordReset,
}) {
  const handleFinish = (values) => {
    const { email, password } = values;
    emailSignInStart(email, password);
  };
  const [form] = Form.useForm();

  const handleReset = () => {
    const email = form.getFieldValue("email");
    sendPasswordReset(email);
  };

  return (
    <div className="login-container">
      <div className="login-logo-container">
        <img src={ImEXOnlineLogo} height="100" width="100" alt="ImEX Online" />
        <Typography.Title>ImEX RPS</Typography.Title>
      </div>
      <Form onFinish={handleFinish} form={form} size="large">
        <Form.Item
          name="email"
          rules={[{ required: true, message: "Please enter a valid email." }]}
        >
          <Input prefix={<UserOutlined />} placeholder="Email" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "Please enter your password." }]}
        >
          <Input
            prefix={<LockOutlined />}
            type="password"
            placeholder="Password"
          />
        </Form.Item>
        {signInError ? (
          <Alert type="error" message={signInError.messagePretty} />
        ) : null}
        <Button
          className="login-btn"
          type="primary"
          htmlType="submit"
          loading={loginLoading}
        >
          Login
        </Button>
        <Form.Item shouldUpdate>
          {() => {
            return (
              <Button
                className="login-btn"
                disabled={!form.getFieldValue("email")}
                onClick={handleReset}
              >
                Reset Password
              </Button>
            );
          }}
        </Form.Item>
      </Form>
      {passwordReset.error && <div>{passwordReset.error}</div>}
    </div>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(SignInPage);
