import React, {useState} from "react";
import { Link, useNavigate } from "react-router-dom";
import Button from "../components/Elements/Buttons";
import axiosInstance from '../api/axiosInstance';
// import { useAuth } from "../context/AuthContext";


const LoginPage = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const navigate = useNavigate();
  // const { isAuthenticated } = useAuth();

  // useEffect(() => {
  //   if (isAuthenticated) {
  //     navigate('/'); // Redirect ke halaman login jika tidak terautentikasi
  //   }
  // }, [isAuthenticated, navigate]);

  const handleSubmit = async (e) => {
    e.preventDefault();    
    setError('');
    try {
      const response = await axiosInstance.post('/login', {
        email,
        password,
      });
      localStorage.setItem('token', response.data.token);
      navigate('/');
    } catch (error) {
      console.log('Full error object:', error);
    
      if (error.response) {
        // console.log('Error response:', error.response);
        const errorMessage = error.response.data.meta.message || 'Terjadi kesalahan. Coba lagi nanti.';
        setError(errorMessage);
      } else if (error.request) {
        console.log('Error request:', error.request);
        setError('Tidak dapat terhubung ke server. Coba lagi nanti.');
      } else {
        console.log('Error message:', error.message);
        setError('Terjadi kesalahan. Coba lagi nanti.');
      }
    }
    
  }
  return (
    <>
      <div className="flex justify-center items-center min-h-screen">
        <div className="grid xl:w-[85%] w-[90%] items-center lg:flex lg:justify-between  lg:gap-20 lg:border-2 lg:shadow-2xl ">
          {/* <!-- Bagian Gambar --> */}
          <div className="flex flex-col items-center justify-center mb-8 md:mb-0">
            {/* card */}
            <div className="hidden lg:flex lg:justify-center lg:items-center">
              <div className="relative bg-[#D0BFFF] xl:w-[35rem] xl:h-[35rem]  w-[30rem] h-[30rem] rounded-lg flex items-center justify-center">
                <div className="relative bg-white xl:w-[30rem] xl:h-[30rem] w-[27rem] h-[27rem] rounded-lg flex items-center justify-center bg-opacity-50">
                  <img
                    src="/image/login-pic.png"
                    alt="gambar"
                    className="absolute top-[50px] left-[250px] transform -translate-x-1/2 w-[28rem] h-[25rem]"
                  />
                  <div className="text-center"></div>
                </div>
              </div>
            </div>
            {/* end card */}
            {/* image */}
            <img
              src="/image/login-pic.png"
              alt="Login"
              className="block w-[70%] md:w-[50%] lg:hidden xl:hidden"
            />
            {/* end image */}
          </div>
          {/* <!-- Bagian Form --> */}
          <form onSubmit={handleSubmit} className="space-y-3 lg:w-1/3 w-full xl:w-1/3  xl:mx-20 ">
            <div>
              <h1 className="text-2xl font-bold text-[#8A6BDB]">Login</h1>
              <p className="md:text-xl text-xl">Login to your account</p>
            </div>
            <div>
              <label htmlFor="email" className="text-slate-800 text-lg">Email</label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                className="placeholder:p-2 placeholder:text-md border-2 block w-full rounded-lg px-5 py-2 focus:outline-none focus:ring-2 focus:ring-purple-500 transition duration-500"
                placeholder="Enter your email"
              />
            </div>
            <div>
            <InputPw password={password} setPassword={setPassword}/>
            </div>
            <div>
              <Link className="flex justify-end text-md text-blue-500 opacity-70 underline mt-2">
                Forget password?
              </Link>
            </div>
            <div className="grid items-center gap-2">
            {error && <p style={{ color: 'red' }}>{error}</p>}

              <Button variant="text-white text-md" type="submit">Login</Button>
              <p className="text-md justify-center flex">Don't have an account?<Link to={"/register"} className="text-blue-500 text-md font-bold ml-1">Register</Link></p>
            </div>
          </form>
          {/* end form */}
        </div>
      </div>
    </>
  );
};

const InputPw = ({ password, setPassword }) => {
  return (
    <>
      <label className="text-slate-800  text-lg ">Password</label>
      <div class="relative">
        <input value={password}
            onChange={(e) => setPassword(e.target.value)} id="hs-toggle-password" type="password" className="px-4 w-full py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-purple-500 transition duration-500 " placeholder="Enter password" />
        <button type="button" data-hs-toggle-password='{
      "target": "#hs-toggle-password"
    }' className="absolute inset-y-0 end-0 flex items-center z-20 px-3 cursor-pointer text-gray-400 rounded-e-md focus:outline-none focus:text-purple-500">
          <svg className="shrink-0 size-3.5" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path class="hs-password-active:hidden" d="M9.88 9.88a3 3 0 1 0 4.24 4.24"></path>
            <path class="hs-password-active:hidden" d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"></path>
            <path class="hs-password-active:hidden" d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"></path>
            <line class="hs-password-active:hidden" x1="2" x2="22" y1="2" y2="22"></line>
            <path class="hidden hs-password-active:block" d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"></path>
            <circle class="hidden hs-password-active:block" cx="12" cy="12" r="3"></circle>
          </svg>
        </button>
      </div>
    </>

  )
}

export default LoginPage;
