import { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
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";
import { AuthWrapper } from "./AuthWrapper";

const LoginPage = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [hidepass, setHidepass] = useState(true);
  const [IsLoginWithOTP, setLoginWithOtp] = 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 },
  } = useForm({
    resolver: zodResolver(loginSchema),
  });

  const onSubmit = async (data) => {
    setLoading(true);
    try {
      const username = data.username.trim();
      const password = data.password?.trim();

      if (!IsLoginWithOTP) {
        const userCredential = {
          username,
          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: username });
        showToast("OTP has been sent to your email.", "success");
        localStorage.setItem("otpUsername", 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 (
    <div className="col-12 col-lg-5 col-xl-4 d-flex align-items-center p-4 p-sm-5 ">
      <div className="w-100" style={{ maxWidth: 420, margin: "0 auto" }}>
        <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" onSubmit={handleSubmit(onSubmit)}>
          {/* Email */}
          <div className="mb-3 text-start">
            <label htmlFor="username" className="form-label">
              Email
            </label>
            <input
              type="text"
              id="username"
              className={`form-control ${errors.username ? "is-invalid" : ""}`}
              placeholder="Enter your email"
              {...register("username")}
              autoFocus
            />
            {errors.username && (
              <div
                className="invalid-feedback text-start"
                style={{ fontSize: "12px" }}
              >
                {errors.username.message}
              </div>
            )}
          </div>

          {/* Password */}
          {!IsLoginWithOTP && (
            <>
              <div className="mb-3 text-start">
                <label htmlFor="password" className="form-label">
                  Password
                </label>
                <div className="input-group input-group-merge">
                  <input
                    type={hidepass ? "password" : "text"}
                    id="password"
                    className={`form-control ${
                      errors.password ? "is-invalid" : ""
                    }`}
                    placeholder="••••••••"
                    {...register("password")}
                  />
                  <span
                    className="input-group-text cursor-pointer"
                    onClick={() => setHidepass(!hidepass)}
                  >
                    <i className={`bx ${hidepass ? "bx-hide" : "bx-show"}`}></i>
                  </span>
                </div>
                {errors.password && (
                  <div
                    className="invalid-feedback text-start"
                    style={{ fontSize: "12px" }}
                  >
                    {errors.password.message}
                  </div>
                )}
              </div>

              {/* Remember Me + Forgot Password */}
              <div className="mb-3 d-flex justify-content-between align-items-center">
                <div className="form-check">
                  <input
                    type="checkbox"
                    id="remember-me"
                    className="form-check-input"
                    {...register("rememberMe")}
                  />
                  <label className="form-check-label" htmlFor="remember-me">
                    Remember Me
                  </label>
                </div>
                <Link
                  to="/auth/forgot-password"
                  className="text-decoration-none"
                >
                  Forgot Password?
                </Link>
              </div>
            </>
          )}

          {/* Submit */}
          <button
            type="submit"
            className="btn btn-primary w-100"
            disabled={loading}
          >
            {loading
              ? "Please Wait..."
              : IsLoginWithOTP
              ? "Send OTP"
              : "Sign In"}
          </button>

          {/* Login With OTP Button */}
          {!IsLoginWithOTP && (
            <>
              <div className="divider my-4">
                <div className="divider-text">or</div>
              </div>
              <button
                type="button"
                className="btn btn-outline-secondary w-100"
                onClick={() => setLoginWithOtp(true)}
              >
                Login With OTP
              </button>
            </>
          )}
        </form>

        {/* Footer Text */}
        {!IsLoginWithOTP ? (
          <p className="text-center mt-3">
            <span>New on our platform? </span>
            <Link to="/auth/reqest/demo" className="btn btn-link p-0">
              Request a Demo
            </Link>
          </p>
        ) : (
          <div className="text-center mt-3">
            <button
              className="btn btn-link p-0"
              onClick={() => setLoginWithOtp(false)}
            >
              <i className="bx bx-chevron-left scaleX-n1-rtl bx-sm"></i>
              Back to login
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default LoginPage;
