import { IoLogoGoogle } from "react-icons/io";
import {GoogleAuthProvider, getAuth, signInWithPopup} from 'firebase/auth'
import { app } from "../firebase";
import { useDispatch } from "react-redux";
import { loginSuccess } from "../redux/user/userSlice";
import { useNavigate } from "react-router-dom";

const OAuth = () => {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const handleGoogleClick = async() => {
        try {
            const provider = new GoogleAuthProvider()
            const auth = getAuth(app)
            const result = await signInWithPopup(auth, provider)
            const res = await fetch('/server/auth/google', {
                method: 'POST',
                headers:{
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    name: result.user.displayName, 
                    email: result.user.email,
                    photo: result.user.photoURL
                }),
            })
            const data = await res.json();
            dispatch(loginSuccess(data));
            navigate('/')
        } catch (error) {
            console.log('Cannot login with Google', error)
        }
    }


  return (
    <button onClick={handleGoogleClick} type="button" className="flex items-center justify-center text-center bg-red-700 p-2 rounded-md hover:opacity-80 text-white gap-2">
        <IoLogoGoogle className="text-lg"/>
        <div className="uppercase text-xs tracking-wide">Continue with google</div>
    </button>
    
  )
}

export default OAuth