import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { AuthWrapper } from "./AuthWrapper";
import { useNavigate } from "react-router-dom";
import "./page-auth.css";
import AuthRepository from "../../repositories/AuthRepository";
import showToast from "../../services/toastService";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

const LoginPage = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [hidepass, setHidepass] = useState(true);
  const [IsLoginWithOTP, setLoginWithOtp] = useState(false);
  const [IsTriedOTPThrough, setIsTriedOTPThrough] = useState(false);
  const now = Date.now();

  const loginSchema = IsLoginWithOTP
    ? z.object({
        username: z.string().email({ message: "Valid email required" }),
      })
    : z.object({
        username: z.string().email({ message: "Valid email required" }),
        password: z.string().min(1, { message: "Password required" }),
        rememberMe: z.boolean(),
      });

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    getValues,
  } = useForm({
    resolver: zodResolver(loginSchema),
  });

  const onSubmit = async (data) => {
    setLoading(true);

    try {
      if (!IsLoginWithOTP) {
        const userCredential = {
          username: data.username,
          password: data.password,
        };
        const response = await AuthRepository.login(userCredential);
        localStorage.setItem("jwtToken", response.data.token);
        localStorage.setItem("refreshToken", response.data.refreshToken);
        setLoading(false);
        navigate("/dashboard");
      } else {
        await AuthRepository.sendOTP({ email: data.username });
        localStorage.setItem("otpUsername", data.username);
        localStorage.setItem("otpSentTime", now.toString());
        navigate("/auth/login-otp");
      }
    } catch (err) {
      showToast("Invalid username or password.", "error");
      setLoading(false);
    }
  };

  useEffect( () =>
  {    const otpSentTime = localStorage.getItem("otpSentTime");
    if (localStorage.getItem("otpUsername") && IsLoginWithOTP && now - Number(otpSentTime) < 10 * 60 * 1000) {
      navigate("/auth/login-otp");
    }
  }, [IsLoginWithOTP]);
  return (
    <AuthWrapper>
      <h4 className="mb-2">Welcome to PMS!</h4>
      <p className="mb-4">
        {IsLoginWithOTP
          ? "Enter your email to receive a one-time password (OTP)."
          : "Please sign-in to your account and start the adventure."}
      </p>
      <form
        id="formAuthentication"
        className="mb-3"
        onSubmit={handleSubmit(onSubmit)}
      >
        <div className="mb-2">
          <label htmlFor="username" className="form-label">
            Email or Username
          </label>
          <input
            type="text"
            className="form-control"
            id="username"
            {...register("username")}
            placeholder="Enter your email or username"
            autoFocus
          />
          {errors.username && (
            <div
              className="danger-text text-start"
              style={{ fontSize: "12px" }}
            >
              {errors.username.message}
            </div>
          )}
        </div>

        {!IsLoginWithOTP && (
          <>
            <div className="mb-3 form-password-toggle">
              <label className="form-label" htmlFor="password">
                Password
              </label>
              <div className="input-group input-group-merge">
                <input
                  type={hidepass ? "password" : "text"}
                  autoComplete="true"
                  id="password"
                  {...register("password")}
                  className="form-control"
                  placeholder="••••••••••••"
                />
                <button
                  type="button"
                  className="btn border-top border-end border-bottom"
                  onClick={() => setHidepass(!hidepass)}
                  style={{
                    borderTopLeftRadius: 0,
                    borderBottomLeftRadius: 0,
                    borderLeft: 0,
                  }}
                >
                  {hidepass ? (
                    <i className="bx bx-hide" />
                  ) : (
                    <i className="bx bx-show" />
                  )}
                </button>
              </div>
              {errors.password && (
                <div
                  className="danger-text text-start"
                  style={{ fontSize: "12px" }}
                >
                  {errors.password.message}
                </div>
              )}
            </div>

            <div className="mb-3 d-flex justify-content-between">
              <div className="form-check d-flex">
                <input
                  className="form-check-input"
                  type="checkbox"
                  id="remember-me"
                  {...register("rememberMe")}
                />
                <label className="form-check-label ms-2">Remember Me</label>
              </div>
              <Link to="/auth/forgot-password">Forgot Password?</Link>
            </div>
          </>
        )}

        <div className="mb-3">
          <button
            aria-label="Submit form"
            className="btn btn-primary d-grid w-100 mb-2"
            type="submit"
          >
            {loading
              ? "Please Wait"
              : IsLoginWithOTP
              ? "Continue with OTP"
              : "Sign In"}
          </button>
          {!IsLoginWithOTP && (
            <button
              aria-label="loginwithotp"
              type="button"
              onClick={() => setLoginWithOtp(true)}
              className="btn btn-primary w-100"
            >
              login With OTP
            </button>
          )}
        </div>
      </form>

      <p className="text-center">
        <span>New on our platform? </span>
        {IsLoginWithOTP ? (
          <a
            className="text-primary cursor-pointer"
            onClick={() => setLoginWithOtp(false)}
          >
            Login With Password
          </a>
        ) : (
          <Link to="/auth/reqest/demo" className="registration-link">
            Request a Demo
          </Link>
        )}
      </p>
    </AuthWrapper>
  );
};

export default LoginPage;
