import { 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 loginScheam = z.object({
  username: z.string().email(),
  password: z.string().min(1, { message: "Password required" }),
  rememberMe: z.boolean(),
});

const LoginPage = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [hidepass, setHidepass] = useState(true);

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

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

    try {
      let 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");
    } catch (err) {
       showToast("Invalid username or password.","error")
      setLoading(false);
    }
  };

  return (
    <AuthWrapper>
      <h4 className="mb-2">Welcome to PMS!</h4>
      <p className="mb-4">
        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")}
            name="username"
            placeholder="Enter your email or username"
            autoFocus
          />
          {errors.username && (
            <div
              className="danger-text text-start"
              style={{ fontSize: "12px" }}
            >
              {errors.username.message}
            </div>
          )}
        </div>
       <div className="mb-3 ">
          <label className="form-label" htmlFor="password">Password</label>
          <div className="input-group input-group-merge  d-flex align-items-center border rounded px-2">
            <input
              type={hidepass ? "password" : "text"}
              id="password"
              autoComplete="true"
              className="form-control border-0 shadow-none"
              {...register("password")}
              placeholder="&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;&#xb7;"
              style={{ flex: 1 }}
              aria-describedby="password"
            />
            <button
              type="button"
              className="btn btn-link p-0 ms-2"
              style={{ fontSize: "18px", color: "#6c757d", }}
              onClick={() => setHidepass(!hidepass)}
            >
              <i className={`bx ${hidepass ? "bx-hide" : "bx-show"}`} />
            </button>
          </div>
          {errors.password && (
            <p className="danger-text small-text text-start">{errors.password.message}</p>
          )}
        </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"
              name="rememberMe"
              {...register("rememberMe")}
            />
            <label className="form-check-label ms-2">Remember Me</label>
          </div>
          <Link
            aria-label="Go to Forgot Password Page"
            to="/auth/forgot-password"
          >
            <span>Forgot Password?</span>
          </Link>
        </div>
        <div className="mb-3">
          <button
            aria-label="Click me"
            className="btn btn-primary d-grid w-100"
            type="submit"
          >
            {loading ? "Please Wait" : " Sign in"}
          </button>
        </div>
      </form>

      <p className="text-center">
        <span>New on our platform? </span>
        <Link
          aria-label="Go to Register Page"
          to="/auth/reqest/demo"
          className="registration-link"
        >
          <span>Request a Demo</span>
        </Link>
      </p>
    </AuthWrapper>
  );
};

export default LoginPage;
