import { initializeApp } from "firebase/app";
import { MessagePayload, getMessaging, getToken, isSupported, onMessage } from "firebase/messaging";
import { useRouter } from "next/navigation";
import React, { SetStateAction } from "react";

// const firebaseConfig = {
//   apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
//   authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
//   projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
//   storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
//   messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGE_SENDER_ID,
//   appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
//   measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASURMENT_ID
// }
const firebaseConfig = {
  apiKey: "AIzaSyCEboVAhJsyIvpL7AFzbu6GVscLrEDan9I",
  authDomain: "basekcall-5fcf0.firebaseapp.com",
  projectId: "basekcall-5fcf0",
  storageBucket: "basekcall-5fcf0.firebasestorage.app",
  messagingSenderId: "541865336054",
  appId: "1:541865336054:web:e37bfb310f7f4c165720d7",
  measurementId: "G-PLPHCTHJ33"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);


export const getFirebaseMessageToken = async () => {


  const isSupport = await isSupported();
  if (isSupport) {

    const messaging = getMessaging(firebaseApp);
    try {
      let tokenId = await getToken(messaging, {
        // vapidKey: process.env.NEXT_PUBLIC_FIREBASE_VAP_ID_KEY,
        vapidKey: 'BKki6vYng-2Fx3kws9YWoFnwsVMN4xg23uqIku4qQBM20nPfloVCytRlDxqQXHDQXkkLGWjJqBqsNFu_DjrJ-oc',
      });
      return tokenId;
    } catch (error) {
      return ''
    }
  }
  return ''
};


export const onMessageListener = (setNotificationData: (data: any) => void) => {
  try {
    if ("serviceWorker" in navigator && typeof window !== "undefined" && "Notification" in window) {
      const fcmmessaging = getMessaging(firebaseApp);

      const unsubscribe = onMessage(fcmmessaging, (payload: any) => {
        setNotificationData(payload);
      });

      return () => unsubscribe();
    }
  } catch (error) {
    console.error('Error in onMessageListener:', error);
  }
};

export default firebaseApp