import { GoogleAuthProvider, signInWithPopup, setPersistence, browserLocalPersistence } from "firebase/auth";
import { useAuthState } from "react-firebase-hooks/auth";
import { Navigate } from "react-router-dom";
import { auth } from "../firebase";
import { Button } from "@/components/ui/button";

const Login = () => {
  const [user, loading] = useAuthState(auth);

  const handleGoogleLogin = async () => {
    const provider = new GoogleAuthProvider();
    try {
      await setPersistence(auth, browserLocalPersistence);
      await signInWithPopup(auth, provider);
    } catch (error) {
      console.error("Error signing in with Google", error);
    }
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  // If user is logged in, redirect to the home page
  if (user) {
    return <Navigate to="/" />;
  }

  // If no user, show the login button
  return (
    <div className="flex items-center justify-center h-screen">
      <Button onClick={handleGoogleLogin}>Sign in with Google</Button>
    </div>
  );
};

export default Login;