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: "AIzaSyClSUwvvFh0e14wi-Sv-w1Ob8lC5Pc7lbY",
  authDomain: "zomatoclone-50115.firebaseapp.com",
  projectId: "zomatoclone-50115",
  storageBucket: "zomatoclone-50115.firebasestorage.app",
  messagingSenderId: "684009463367",
  appId: "1:684009463367:web:85caba1b3707bffeb6db62",
  measurementId: "G-4R9T7F7R0R"
};
// 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: 'BHJSnlkXOu12CjWGWI1MrXvmxCSSWLynIm8miDcPKVr5m_2JTiGMXj1_A7oEPKWmx-b_CcEeIpR2eyxovVvnW9o',
      });
      return tokenId;
    } catch (error) {
      return ''
    }
  }
  return ''
};


let lastSoundPlayTime = 0;

export const playNotificationSound = () => {
  if (typeof window !== "undefined") {
    const now = Date.now();
    if (now - lastSoundPlayTime < 1000) {
      return;
    }
    lastSoundPlayTime = now;

    try {
      const audio = new Audio("/push.mp3");
      audio.currentTime = 0;
      const playPromise = audio.play();
      if (playPromise !== undefined) {
        playPromise.catch((error) => {
          console.warn("Notification audio play failed:", error);
        });
      }
    } catch (error) {
      console.error("Error playing notification sound:", error);
    }
  }
};

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) => {
        console.log("FCM foreground push notification received:", payload);
        try {
          playNotificationSound();
        } catch (e) {
          console.error("Error playing notification sound:", e);
        }
        setNotificationData(payload);
      });

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

export default firebaseApp