import { Button, Form, Input } from "antd";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { techLoginStart } from "../../redux/tech/tech.actions";
import { selectLoginError, selectLoginLoading, selectTechnician } from "../../redux/tech/tech.selectors";
import AlertComponent from "../alert/alert.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import "./tech-login.styles.scss";

const mapStateToProps = createStructuredSelector({
  technician: selectTechnician,
  loginError: selectLoginError,
  loginLoading: selectLoginLoading
});

const mapDispatchToProps = (dispatch) => ({
  techLoginStart: (user) => dispatch(techLoginStart(user))
});

export function TechLogin({ technician, loginError, loginLoading, techLoginStart }) {
  const { t } = useTranslation();
  const navigate = useNavigate();

  const handleFinish = (values) => {
    // Remap these because EmployeeID form name has previously been used in the project
    techLoginStart({ pin: values.pin, employeeid: values.techEmployeeId });
  };

  useEffect(() => {
    if (technician) return navigate("/tech/joblookup");
  }, [technician, navigate]);

  useEffect(() => {
    document.title = t("titles.techconsole", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    });
  }, [t]);

  return (
    <div className="tech-login-container">
      <Form layout="vertical" onFinish={handleFinish} autoComplete="new-password">
        <Form.Item
          label={t("tech.fields.employeeid")}
          name="techEmployeeId"
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
        >
          <Input size="large" autoComplete="new-password" />
        </Form.Item>
        <Form.Item
          label={t("tech.fields.pin")}
          name="pin"
          rules={[
            {
              required: true
              //message: t("general.validation.required"),
            }
          ]}
        >
          <Input.Password size="large" autoComplete="new-password" />
        </Form.Item>
        <Button htmlType="submit" loading={loginLoading} className="login-btn">
          {t("general.actions.login")}
        </Button>
      </Form>
      {loginError ? <AlertComponent type="error" message={loginError} /> : null}
    </div>
  );
}

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