import { initFirebase } from '@/lib/firebase/initFirebase';
import { UserAuthInfo } from '@/lib/utils/types';
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword } from "firebase/auth";
import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { readUserInfo, initUserInfo } from '@/lib/firebase/firestore/user';



export async function signInWithEmailAndPasswordHandler(email: string, password: string) {
  initFirebase();
  const auth = getAuth();

  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password)

    // Get the relevant user info from the userCredential (match the user Atom)
    const user: UserAuthInfo = {
      uid: userCredential.user.uid,
      email: userCredential.user.email as string,
      emailVerified: userCredential.user.emailVerified,
      displayName: userCredential.user.providerData[0].displayName as string,
      phoneNumber: userCredential.user.providerData[0].phoneNumber as string,
      photoURL: userCredential.user.providerData[0].photoURL as string,
    }

    return { data: user }

  } catch (error: any) {
    switch (error.code) {
      case 'auth/wrong-password':
        return { error: "Wrong password!" }
      case 'auth/user-not-found':
        return { error: "User not found!" }
      default:
        return { error: "Something went wrong!" }
    }
  }
}


export async function createUserWithEmailAndPasswordHandler(email: string, password: string) {
  initFirebase();
  const auth = getAuth();

  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password)
    
    // Get the relevant user info from the userCredential (match the user Atom)
    const user: UserAuthInfo = {
      uid: userCredential.user.uid,
      email: userCredential.user.email as string,
      emailVerified: userCredential.user.emailVerified,
      displayName: userCredential.user.providerData[0].displayName as string,
      phoneNumber: userCredential.user.providerData[0].phoneNumber as string,
      photoURL: userCredential.user.providerData[0].photoURL as string,
    }

    await createUserIfNotExist(user)

    return { data: user }
  } catch (error: any) {
    if (error.code === 'auth/email-already-in-use') {
      return { error: "That email address is already in use!" }
    }
  }

  return { error: "Something went wrong!" }
}


export async function signWithPopupHandler() {
  initFirebase();
  const auth = getAuth();
  await auth.signOut();
  const provider = new GoogleAuthProvider();

  try {
    const result = await signInWithPopup(auth, provider);

    const credential = GoogleAuthProvider.credentialFromResult(result);

    if (!credential) {
      return { error: "Something went wrong!" }
    }

    const token = credential.accessToken;
    // The signed-in user info.
    const user = result.user;

    const _user: UserAuthInfo = {
      uid: user.uid,
      email: user.email as string,
      emailVerified: user.emailVerified,
      displayName: user.displayName as string,
      phoneNumber: user.phoneNumber as string,
      photoURL: user.photoURL as string,
    }

    await createUserIfNotExist(_user)

    return { data: _user }

  } catch (error: any) {
    console.error(error)
  }

  return { error: "Something went wrong!" }
}


export async function signOutHandler() {
  initFirebase();
  const auth = getAuth();
  await auth.signOut();
}


export async function createUserIfNotExist(user: UserAuthInfo) {
  let res = await readUserInfo(user.uid)

  // If user do not exist, add an entry in Firestore
  if (res.error) {
    const res2 = initUserInfo(user.uid)
  }

  // If not, do nothing
}