import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";

const firebaseConfig = {
  apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
  authDomain: `${import.meta.env.VITE_FIREBASE_PROJECT_ID}.firebaseapp.com`,
  projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
  storageBucket: `${import.meta.env.VITE_FIREBASE_PROJECT_ID}.appspot.com`,
  messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
  appId: import.meta.env.VITE_FIREBASE_APP_ID
};

let messaging: any;

try {
  console.log("Initializing Firebase with config:", { ...firebaseConfig, apiKey: '***' });
  const app = initializeApp(firebaseConfig);
  messaging = getMessaging(app);
  console.log("Firebase initialized successfully");
} catch (error) {
  console.error("Error initializing Firebase:", error);
}

async function registerServiceWorker() {
  try {
    console.log("Checking service worker registration status...");
    const registrations = await navigator.serviceWorker.getRegistrations();

    // Check if our service worker is already registered
    const existingRegistration = registrations.find(
      registration => registration.scope === '/' && 
      registration.active?.scriptURL.includes('firebase-messaging-sw.js')
    );

    if (existingRegistration) {
      console.log("Firebase service worker already registered:", existingRegistration);

      // Ensure the service worker is activated
      if (existingRegistration.active) {
        console.log("Service worker is active");
      } else {
        console.log("Waiting for service worker to activate...");
        await new Promise<void>((resolve) => {
          existingRegistration.addEventListener('activate', () => resolve());
        });
        console.log("Service worker activated");
      }

      return existingRegistration;
    }

    console.log("Attempting to register new service worker...");
    const registration = await navigator.serviceWorker.register('/firebase-messaging-sw.js', {
      scope: '/'
    });
    console.log('Service Worker registered successfully:', registration);

    // Wait for the service worker to be activated
    await new Promise<void>((resolve) => {
      if (registration.active) {
        resolve();
      } else {
        registration.addEventListener('activate', () => resolve());
      }
    });

    console.log("Service worker activated successfully");
    return registration;
  } catch (error) {
    console.error('Service Worker registration failed:', error);
    throw error;
  }
}

export async function requestNotificationPermission() {
  try {
    console.log("Starting notification permission request...");

    if (!("Notification" in window)) {
      throw new Error("This browser does not support notifications");
    }

    const permission = await Notification.requestPermission();
    console.log("Notification permission status:", permission);

    if (permission === "granted") {
      if (!messaging) {
        throw new Error("Firebase messaging not initialized");
      }

      console.log("Registering service worker...");
      await registerServiceWorker();

      console.log("Requesting FCM token...");
      const token = await getToken(messaging, {
        vapidKey: import.meta.env.VITE_FIREBASE_VAPID_KEY,
      });
      console.log("FCM Token obtained:", token);

      if (!token) {
        throw new Error("Failed to obtain FCM token");
      }

      return token;
    }

    console.log("Notification permission not granted");
    return null;
  } catch (error) {
    console.error("Error in requestNotificationPermission:", error);
    throw error;
  }
}

export function onMessageListener() {
  if (!messaging) {
    console.warn("Firebase messaging not initialized, cannot set up message listener");
    return () => {};
  }

  return onMessage(messaging, (payload) => {
    console.log("Foreground message received:", payload);

    // Create a notification using the Notifications API
    if (Notification.permission === "granted") {
      const { title, body } = payload.notification || {};
      try {
        const notification = new Notification(title || "New Notification", {
          body: body || "",
          icon: "/logo.png",
          badge: "/logo.png",
          tag: 'notification',
          requireInteraction: true,
          actions: [
            {
              action: 'open',
              title: 'Open'
            }
          ]
        });

        notification.onclick = () => {
          console.log("Notification clicked");
          window.focus();
          notification.close();
        };

        console.log("Browser notification created successfully");
      } catch (error) {
        console.error("Error creating browser notification:", error);
      }
    } else {
      console.warn("Notification permission not granted, cannot show notification");
    }

    return payload;
  });
}