import { LockOutlined } from "@ant-design/icons";
import { Button, Form, Input, Result, Typography } from "antd";
import React, { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import ImEXOnlineLogo from "../../assets/logo192.png";
import { auth } from "../../firebase/firebase.utils";
import { checkActionCode } from "@firebase/auth";
import { validatePasswordResetStart } from "../../redux/user/user.actions";
import { selectPasswordReset } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import "./user-validate-pw-reset.styles.scss";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";

const mapStateToProps = createStructuredSelector({
  passwordReset: selectPasswordReset,
});
const mapDispatchToProps = (dispatch) => ({
  validatePasswordReset: (emailAndPin) =>
    dispatch(validatePasswordResetStart(emailAndPin)),
});

export function UserValidatePwReset({
  passwordReset,
  validatePasswordReset,
  oobCode,
}) {
  const { t } = useTranslation();
  const [codeValid, setCodeValid] = useState({ loading: true });
  const handleFinish = (values) => {
    validatePasswordReset({ code: oobCode, password: values.password });
  };

  useEffect(() => {
    async function checkCodeValid() {
      try {
        const codeValid = await checkActionCode(auth, oobCode);

        setCodeValid({ loading: false, ...codeValid });
      } catch (error) {
        setCodeValid({ loading: false, ...error });
      }
    }
    checkCodeValid();
  }, [oobCode]);

  if (codeValid.loading) return <LoadingSpinner />;

  if (codeValid.code)
    return (
      <div>
        <Result status="error" title={codeValid.message} />
      </div>
    );

  if (passwordReset.success)
    return (
      <Result
        status="success"
        title={t("general.labels.passwordresetvalidatesuccess")}
        subTitle={t("general.labels.passwordresetvalidatesuccess_sub")}
        extra={[
          <Link to={`/manage`}>
            <Button>{t("general.labels.signin")}</Button>
          </Link>,
        ]}
      />
    );

  return (
    <div className="reset-container">
      <div className="reset-logo-container">
        <img src={ImEXOnlineLogo} height="100" width="100" alt="ImEX Online" />
        <Typography.Title>{t("titles.app")}</Typography.Title>
      </div>
      <Typography.Title level={3}>
        {t("titles.resetpasswordvalidate")}
      </Typography.Title>

      <Form onFinish={handleFinish} size="large" layout="vertical">
        <Form.Item
          label={t("general.labels.password")}
          name="password"
          rules={[
            {
              required: true,
              //message: t("general.validation.required"),
            },
          ]}
        >
          <Input
            prefix={<LockOutlined />}
            type="password"
            placeholder={t("general.labels.password")}
          />
        </Form.Item>
        <Form.Item
          label={t("general.labels.confirmpassword")}
          name="password-confirm"
          dependencies={["password"]}
          rules={[
            {
              required: true,
              //message: t("general.validation.required"),
            },
            ({ getFieldValue }) => ({
              validator(rule, value) {
                if (!value || getFieldValue("password") === value) {
                  return Promise.resolve();
                }
                return Promise.reject(t("general.labels.passwordsdonotmatch"));
              },
            }),
          ]}
        >
          <Input
            prefix={<LockOutlined />}
            type="password"
            placeholder={t("general.labels.password")}
          />
        </Form.Item>
        {passwordReset.error ? (
          <AlertComponent message={passwordReset.error} type="warning" />
        ) : null}
        <Button type="primary" className="reset-btn" htmlType="submit">
          {t("general.actions.submit")}
        </Button>
      </Form>
    </div>
  );
}

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