import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Form, Input, Typography } from "antd";
import queryString from "query-string";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import RomeLogo from "../../assets/RomeOnlineBlue.png";
import ImEXOnlineLogo from "../../assets/logo192.png";
import { emailSignInStart, sendPasswordReset } from "../../redux/user/user.actions";
import { selectCurrentUser, selectLoginLoading, selectSignInError } from "../../redux/user/user.selectors";
import { selectIsPartsEntry } from "../../redux/application/application.selectors";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import AlertComponent from "../alert/alert.component";
import "./sign-in-form.styles.scss";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
  signInError: selectSignInError,
  loginLoading: selectLoginLoading,
  isPartsEntry: selectIsPartsEntry
});

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

export function SignInComponent({ emailSignInStart, currentUser, signInError, loginLoading, isPartsEntry }) {
  const { redirect } = queryString.parse(useLocation().search);
  const navigate = useNavigate();

  const { t } = useTranslation();
  const handleFinish = (values) => {
    const { email, password } = values;
    emailSignInStart(email, password);
  };
  const [form] = Form.useForm();

  useEffect(() => {
    if (currentUser.authorized === true) {
      navigate(redirect || (isPartsEntry ? "/parts/" : "/manage/"));
    }
  }, [currentUser, redirect, navigate, isPartsEntry]);

  useEffect(() => {
    const handleSeamlessLogin = (event) => {
      console.log("Received message event:", event); // Log the received message event

      if (event.data?.type !== "seamlessLoginRequest") return; // Filter to only handle relevant messages

      const { email, password } = event.data || {}; // Use event.data instead of event.detail
      const requestOrigin = event.origin; // Use event.origin automatically

      // Validate input (rest of your code remains the same)
      if (!email || !password) {
        window.parent.postMessage(
          { type: "seamlessLoginResponse", status: "error", message: "Email and password are required" },
          requestOrigin || "*"
        );
        return;
      }

      // Check if the user is already logged in
      if (currentUser.authorized === true) {
        console.log("User is already logged in, redirecting...");
        navigate(redirect || (isPartsEntry ? "/parts/" : "/manage/"));
        window.parent.postMessage({ type: "seamlessLoginResponse", status: "already_logged_in" }, requestOrigin || "*");
        return;
      }

      // Proceed with sign-in if not logged in
      emailSignInStart(email, password);
      window.parent.postMessage({ type: "seamlessLoginResponse", status: "login_attempted" }, requestOrigin || "*");
    };

    window.addEventListener("message", handleSeamlessLogin);

    return () => {
      window.removeEventListener("message", handleSeamlessLogin);
    };
  }, [emailSignInStart, currentUser, navigate, redirect, isPartsEntry]);

  return (
    <div className="login-container">
      <div className="login-logo-container">
        <img
          src={InstanceRenderManager({
            imex: ImEXOnlineLogo,
            rome: RomeLogo
          })}
          width={InstanceRenderManager({ imex: 200, rome: 200 })}
          alt={InstanceRenderManager({
            imex: t("titles.imexonline"),
            rome: t("titles.romeonline")
          })}
        />
        <Typography.Title>
          {InstanceRenderManager({
            imex: t("titles.imexonline"),
            rome: t("titles.romeonline")
          })}
        </Typography.Title>
      </div>
      <Form onFinish={handleFinish} form={form} size="large">
        <Form.Item
          name="email"
          rules={[
            {
              required: true,
              message: t("general.validation.required", { label: "Email" })
            }
          ]}
        >
          <Input prefix={<UserOutlined />} placeholder={t("general.labels.username")} />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: t("general.validation.required", { label: "Password" })
            }
          ]}
        >
          <Input prefix={<LockOutlined />} type="password" placeholder={t("general.labels.password")} />
        </Form.Item>
        {signInError ? <AlertComponent type="error" title={t(`users.errors.signinerror.${signInError.code}`)} /> : null}
        <Button className="login-btn" type="primary" htmlType="submit" loading={loginLoading}>
          {t("general.actions.login")}
        </Button>
      </Form>
      <Link to={"/resetpassword"}>
        <Button>{t("general.actions.resetpassword")}</Button>
      </Link>
    </div>
  );
}

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