import React,  { useState, useEffect, useContext} from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom'; // Assuming you use react-router-dom
import axios from 'axios'; // For the Google login
// New line:
import { AuthContext } from "../auth/AuthContext.jsx";  
import flag1 from '../assets/flag1.jpg';
import { GoogleOAuthProvider, GoogleLogin } from '@react-oauth/google';

export default function Login() {
  const [email, setEmail] = useState('');
  const GOOGLE_CLIENT_ID = "764706231535-61o8hs5bui31at36psk5ar8kbcfvsmnj.apps.googleusercontent.com";
  const [password, setPassword] = useState('');
  const [errorMsg, setErrorMsg] = useState('');
  const [successMsg, setSuccessMsg] = useState('');
  const [showPassword, setShowPassword] = useState(false); // For handleTogglePassword

  // Hooks for routing and context
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { setAuth } = useContext(AuthContext);
  const { login } = useContext(AuthContext);

  const handleLogin = async () => {
    try {
      // Call login from context
      const user = await login(email, password);
  
      console.log("🔍 returned user from login:", user);
  
      if (!user) {
        setErrorMsg("Login failed. Please check your credentials.");
        return;
      }
  
      // Persist user in context and localStorage is already done in AuthContext
      // Log key info for debugging
      console.log("📧 email:", user.email);
      console.log("🔑 permissions:", user.user_permissions);
  
      // Check permissions
      const hasPermissions =
        Array.isArray(user.user_permissions) && user.user_permissions.length > 0;
  
      if (user.is_superuser || hasPermissions) {
        console.log("➡️ Navigating admin/officer to dashboard");
        navigate("/admin/dashboard");
      } else {
        console.log("➡️ Navigating citizen to home");
        navigate("/");
      }
    } catch (err) {
      console.error("Login error:", err);
      setErrorMsg("Login failed. Please try again.");
    }
  };
  
  

const handleGoogleLoginSuccess = async (credentialResponse) => {
  try {
    // exchange Google token for backend JWT 
    const response = await axios.post(`${process.env.REACT_APP_API_BASE_URL}/google-auth/`, {
      access_token: credentialResponse.credential,
    });

    const { access, refresh } = response.data;
    if (!access || !refresh) throw new Error("Invalid Google login response");

    // now fetch user/me (same as email login does in auth.js) 
    const userResponse = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/user/me/`, {
      headers: { Authorization: `Bearer ${access}` },
    });

    const userData = userResponse.data;

    // persist everything in localStorage (reuse saveAuthData helper if you like)
    localStorage.setItem("accessToken", access);
    localStorage.setItem("refreshToken", refresh);
    localStorage.setItem("userName", userData.username);

    // update context with the actual user object (with permissions)
    setAuth(userData);

    navigate("/dashboard/home"); // safe: permissions already fetched
  } catch (error) {
    console.error("Google login failed", error);
    setErrorMsg("Google login failed. Please try again.");
  }
};

  const handleTogglePassword = () => {
    setShowPassword((prev) => !prev);
  };

  useEffect(() => {
    const activationError = searchParams.get('error');
    const activationSuccess = searchParams.get('success');
    
    if (activationError) {
      setErrorMsg("Account activation failed. The link may be invalid or expired.");
    } else if (activationSuccess) {
      setSuccessMsg("Account successfully activated! You can now log in.");
    }
  }, [searchParams]);

  
  return (
    <GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
    <div className="relative min-h-screen flex items-center justify-end overflow-hidden">
      {/* Background image */}
      <div
        className="absolute inset-0 w-full h-full z-0"
        style={{ 
          backgroundImage: `linear-gradient(rgba(59, 130, 246, 0.25), rgba(59, 130, 246, 0.25)), url(${flag1})`, 
          backgroundSize: 'cover', 
          backgroundPosition: 'center'
        }}
        aria-hidden="true"
      />
      <div className="relative z-20 w-full max-w-md p-4 md:p-6 bg-white/90 rounded-2xl shadow-2xl animate-fade-in-up flex flex-col gap-2 mr-4 md:mr-16 lg:mr-32 xl:mr-48">
        <h2 className="text-3xl font-extrabold mb-4 text-blue-800 text-center drop-shadow">Login</h2>
        <form className="space-y-4" onSubmit={(e) => { e.preventDefault(); handleLogin(); }}>

        {errorMsg && <p className="text-red-600 font-medium text-center">{errorMsg}</p>}
        {successMsg && <p className="text-green-600 font-medium text-center">{successMsg}</p>}
        <div>
    <label className="block text-blue-900 font-semibold mb-1">Email</label>
    <input 
      type="email" 
      value={email} // BIND
      onChange={(e) => setEmail(e.target.value)} // BIND
      className="w-full px-4 py-2 border border-blue-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 bg-blue-50/60 transition" 
    />
  </div>
  <div>
    <label className="block text-blue-900 font-semibold mb-1">Password</label>
    <div className="relative"> {/* Use a wrapper for the eye icon */}
      <input 
        type={showPassword ? "text" : "password"} // TOGGLE TYPE
        value={password} // BIND
        onChange={(e) => setPassword(e.target.value)} // BIND
        className="w-full px-4 py-2 border border-blue-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 bg-blue-50/60 transition pr-10" 
      />
      {/* Example for the toggle button (you might need an icon library like Heroicons) */}
      <button 
        type="button" 
        onClick={handleTogglePassword} 
        className="absolute inset-y-0 right-0 pr-3 flex items-center text-sm leading-5 text-blue-600"
      >
        {showPassword ? "Hide" : "Show"} {/* Replace with an eye icon */}
      </button>
    </div>
  </div>
  <button 
    type="submit" 
    className="w-full bg-gradient-to-r from-blue-700 to-blue-500 text-white py-2 rounded-lg font-bold shadow hover:from-blue-800 hover:to-blue-600 transition mb-2"
  >
    Login
  </button>

  <div className="mt-4">
    {/* You'd replace this with the actual GoogleLogin component from your library */}
    <button className="w-full flex items-center justify-center bg-white border border-gray-300 text-gray-800 py-2 rounded-lg font-semibold shadow hover:bg-gray-50 transition">
        {/* The GoogleLogin component would be here, e.g., <GoogleLogin onSuccess={handleGoogleLoginSuccess} onError={...} /> */}
        Sign in with Google
    </button>
</div>
          <div className="flex justify-between text-sm text-blue-900">
            <a href="/forgot-password" className="text-blue-600 hover:underline font-semibold">Forgot password?</a>
            <a href="/register" className="text-blue-600 hover:underline font-semibold">Register</a>
          </div>
        </form>
      </div>
    </div>
    </GoogleOAuthProvider>
  );
}
