import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import axiosInstance from "../../config/axiosInstance";
import { login } from "../../store/slices/authSlices";
import { Eye, EyeOff, Lock, Mail, Shield, Loader } from "lucide-react";
import "./Login.css";

const Login = () => {
  const [showPassword, setShowPassword] = useState(false);
  const [apiErr, setApiErr] = useState(null);
  const dispatch = useDispatch();
  const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
  // const { fetchUser } = useUser();

  const loginSchema = yup
    .object({
      email: yup.string().email("Invalid email").required("Email is required"),
      password: yup
        .string()
        .min(6, "Make lenght more.")
        .required("Password is required"),
    })
    .required();
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(loginSchema),
  });
  const navigate = useNavigate();

  // useCheckAdminLoggedIn();

  const handleLogin = async (data) => {
    // try {
    //   // const response = await axiosInstance.post("/auth/login", data);
    //   dispatch(login(data))

    //   // if (response.status === 200) {
    //   //   navigate("/admin/dashboard");
    //   //   // fetchUser();
    //   // }
    // } catch (error) {
    //   if (error.response) {
    //     setApiErr(error.response.data?.message);
    //   } else if (error.request) {
    //     setApiErr(
    //       "No response from server. Please check your internet connection."
    //     );
    //   } else {
    //     setApiErr(error.message || "Something went wrong.");
    //   }
    // }
    dispatch(login(data));
    if (isAuthenticated) {
      navigate("/admin/dashboard");
    }
  };

  const auth = useSelector((state) => state.auth);
  // console.log(auth);

  return (
    <div className="login__container">
      <div className="login__card">
        <div className="login__header">
          <div className="login__logo-container">
            {/* <Shield className="login__logo-icon" size={40} /> */}
            <h1 className="login__logo-heading">Admin Portal</h1>
          </div>
          <p className="login__subtitle">Sign in to access your dashboard</p>
        </div>

        <form onSubmit={handleSubmit(handleLogin)} className="login__form">
          {/* {error && (
            <div className="error-message">
              <span>{error}</span>
            </div>
          )} */}
          {apiErr && (
            <p className="admin-login__err admin-login__err-server">{apiErr}</p>
          )}

          <div className="input-group">
            <div className="input-wrapper">
              {/* <Mail className="input-icon" size={20} /> */}
              <input
                type="email"
                placeholder="Enter your email"
                // value={email}
                // onChange={(e) => setEmail(e.target.value)}
                className="form-input"
                required
                {...register("email")}
              />
              {errors.email && (
                <p className="admin-login__err">{errors.email?.message}</p>
              )}
            </div>
          </div>

          <div className="input-group">
            <div className="input-wrapper">
              {/* <Lock className="input-icon" size={20} /> */}
              <input
                type={showPassword ? "text" : "password"}
                placeholder="Enter your password"
                // value={password}
                // onChange={(e) => setPassword(e.target.value)}
                className="form-input"
                required
                {...register("password")}
              />
              {errors.password && (
                <p className="admin-login__err">{errors.password?.message}</p>
              )}
              <button
                type="button"
                className="password-toggle"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? <EyeOff size={20} /> : <Eye size={20} />}
              </button>
            </div>
          </div>

          <div className="form-options">
            <label className="remember-me">
              <input type="checkbox" />
              <span className="checkmark"></span>
              Remember me
            </label>
            <a href="#" className="forgot-password">
              Forgot password?
            </a>
          </div>

          <button type="submit" className={`login__btn`}>
            Sign In
          </button>
        </form>

        <div className="login__footer">
          <p>
            Need help? <a href="#">Contact Support</a>
          </p>
        </div>
      </div>
    </div>
  );
};

export default Login;
