// Import necessary components
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { setCurrentUser} from "../../utils/tokenService";
import { LoginEnvironment } from "../examples/LoginEnviornment";
import "../../assets/css/login.css";

// Google logo SVG
const GoogleLogo = () => (
  <svg className="google-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 488 512">
    <path fill="#4285F4" d="M488 261.8C488 403.3 391.1 504 248 504 110.8 504 0 393.2 0 256S110.8 8 248 8c66.8 0 123 24.5 166.3 64.9l-67.5 64.9C258.5 52.6 94.3 116.6 94.3 256c0 86.5 69.1 156.6 153.7 156.6 98.2 0 135-70.4 140.8-106.9H248v-85.3h236.1c2.3 12.7 3.9 24.9 3.9 41.4z" />
  </svg>
);

/**
 * Login Component - Handles user authentication
 * Provides form for entering credentials and submitting login request
 * 
 * The component includes:
 * - Form for email/password input
 * - Error handling for invalid inputs
 * - API integration for authentication
 * - Navigation to dashboard on success
 * - Links to password reset and registration
 */
const Login = () => {
  // Hook for navigation after login success/failure
  const navigate = useNavigate();

  // State for form fields and UI controls
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [isPasswordVisible, setIsPasswordVisible] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  const [error, setError] = useState("");

  // Destructure text content from environment configuration
  const {
    loginText2,
    loginText3,
  } = LoginEnvironment;

  /**
   * Toggle password visibility between plain text and masked
   * Used for the show/hide password functionality
   */
  const togglePasswordVisibility = () => {
    setIsPasswordVisible(!isPasswordVisible);
    console.log("Password visibility toggled:", !isPasswordVisible ? "shown" : "hidden");
  };

  /**
   * Handle login form submission
   * Validates inputs, makes API request, and handles response
   * 
   * @param {Event} e - The form submission event
   */
  const login = async (e) => {
    e.preventDefault();
    console.log("Login form submitted with email:", username);
    setError("");

    // Input validation
    if (!username || !password) {
      console.log("Login validation failed: Empty email or password");
      setError("Email and Password are required");
      return;
    }

    try {
      console.log("Attempting login API request to:", `${process.env.REACT_APP_API_URL}token/session`);

      // API request to authentication endpoint
      const response = await fetch(`${process.env.REACT_APP_API_URL}token/session`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email: username,
          password,
        }),
      });

      if (response.ok) {
        // Handle successful login
        console.log("Login successful ",response);
        const responseData = await response.json();
        console.log("Login successful ",responseData);
        const authToken = responseData.item.token;
        console.log("Login successful, token received");

        // Store authentication token
        setCurrentUser(JSON.stringify(responseData.item));
        // setToken(authToken);
        console.log("Token stored in local storage, redirecting to dashboard");

        // Redirect to dashboard
        navigate("/admin/index");
      } else {
        // Handle login failure
        const errorResponse = await response.json();
        console.log("Login failed with status:", response.status, "Message:", errorResponse.operationMessage);
        setError("Login failed: " + (errorResponse.operationMessage || "Invalid email or password"));
      }
    } catch (error) {
      // Handle connection errors
      console.error("Login API error:", error.message);
      // setError(`An error occurred during login: ${error.message}`);
      setError(`Something went wrong !!!!`);

    }
  };

  /**
   * Navigate to password reset page
   * 
   * @param {Event} e - The click event
   */
  const handleForgetPassword = (e) => {
    e.preventDefault();
    console.log("Navigating to password reset page");
    navigate("/auth/resetpassword");
  };

  /**
   * Navigate to account registration page
   * Passes email to registration if already entered
   * 
   * @param {Event} e - The click event
   */
  const handleCreateAccountClick = (e) => {
    e.preventDefault();
    if (username) {
      console.log("Navigating to registration with email:", username);
      navigate("/auth/register", { state: { email: username } });
    } else {
      console.log("Navigating to registration without email");
      navigate("/auth/register");
    }
  };

   {/* Right side - Image */}
  const renderImage = () => {
    // Get the image URL from LoginEnvironment
    return (
      <div className="login-image-container">
        <div className="login-image" style={{
          backgroundColor: '#f5f5f5',
          backgroundImage: `url(${LoginEnvironment.loginImageURL})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center'
        }}></div>
      </div>
    );
  };

  {/* Left side - Login Form */}
  const renderLoginForm = () => (
    <div className="login-form-container">
      <div className="welcome-text">
        <h1 className="welcome-title">{LoginEnvironment.loginHeading}</h1>
        <p className="welcome-subtitle">{LoginEnvironment.loginHeading2}</p>
      </div>

      {/* Error display - shows authentication errors */}
      {error && (
        <div className="alert-message alert-error">{error}</div>
      )}

      {/* Login form with email and password fields */}
      <form onSubmit={login}>
        <label className="form-label" htmlFor="email">Email</label>
        <input
          id="email"
          className="form-input"
          type="text"
          placeholder="Enter your email (sysadmin)"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          required
        />

        <label className="form-label" htmlFor="password">Password</label>
        <input
          id="password"
          className="form-input"
          type={isPasswordVisible ? "text" : "password"}
          placeholder="Enter your password (test3)"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
        />

        {/* Additional form options */}
        <div className="form-extra">
          <div className="remember-me">
            <input
              type="checkbox"
              id="remember"
              className="remember-checkbox"
              checked={rememberMe}
              onChange={() => setRememberMe(!rememberMe)}
            />
            <label htmlFor="remember">Remember me</label>
          </div>
          <a href="#" className="forgot-password" onClick={handleForgetPassword}>
            Forgot password
          </a>
        </div>

        {/* Login button */}
        <button type="submit" className="login-btn signin-btn">
          Sign in
        </button>

        {/* Social login options */}
        <button type="button" className="login-btn google-btn">
          <GoogleLogo />
          Sign in with Google
        </button>
      </form>

      {/* Registration link */}
      {LoginEnvironment.isSignup && (
        <div className="signup-link-container">
          Don't have an account?
          <a href="#" className="signup-link" onClick={handleCreateAccountClick}>
            Sign up
          </a>
        </div>
      )}
    </div>
  )


  return (
    <>
      {/* Style tag inside JSX */}
      <style>
        {`
          html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
            box-sizing: border-box;
          }
          
          .login-container {
            display: flex;
            width: 100vw;
            height: 100vh;
          }
        `}
      </style>

      {/* Login Page JSX */}
      <div className="login-container">
        {LoginEnvironment.templateNo === "Template 1" ? (
          <>
            {renderLoginForm()}
            {renderImage()}
          </>
        ) : (
          <>
            {renderImage()}
            {renderLoginForm()}
          </>
        )}
      </div>
    </>
  );
};


export default Login;



// export const LoginEnvironment = {
//   templateNo: "Template 1",
//   loginHeading: "Sign in With ",
//   loginHeading2: "Or sign in with credentials",
//   isSignup: true,
//   loginSignup: "Don't have an account?",
//   loginSignup2: "Sign up here!",
//   loginImage: "Login Illustration",
//   loginImageURL: "/path/to/image.jpg",
//   loginText1:"Remember me",
//   loginText2:"Forgot password?",
//   loginText3:"Create new account",
//   buttonTitle:"Github",
//   buttonTitle2:"Google",
// };