"use client";

import { useEffect, useState, useRef } from "react";
import { initializeApp, getApps } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
import AuthService from "../services/AuthService";
import { setFCMToken } from "../utils/api";

const firebaseConfig = {
  apiKey: "AIzaSyBZV7KBLRJSTApahfrO8lBesmIM3zNRSaY",
  authDomain: "sweet-home-b2766.firebaseapp.com",
  projectId: "sweet-home-b2766",
  storageBucket: "sweet-home-b2766.firebasestorage.app",
  messagingSenderId: "602865114600",
  appId: "1:602865114600:web:ed9b6754940507a6ab585d",
  measurementId: "G-M2V95NBJLX",
};

const app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];

export default function NotificationHandler() {
  const [notification, setNotification] = useState(null);
  const [showPrompt, setShowPrompt] = useState(false);
  const initialized = useRef(false);

  useEffect(() => {
    function checkAuth() {
      if (initialized.current) return;

      if (!AuthService.getToken()) return;
      initialized.current = true;

      if ("Notification" in window) {
        if (Notification.permission === "default") {
          setShowPrompt(true);
        } else if (Notification.permission === "granted") {
          setupFCM();
        }
      }
    }

    // Check immediately
    checkAuth();

    // Also check when auth token changes (login via client-side navigation)
    const interval = setInterval(() => {
      if (!initialized.current && AuthService.getToken()) {
        checkAuth();
      }
    }, 1000);

    // Check on route change (visibility)
    const onVisibility = () => {
      if (document.visibilityState === "visible") checkAuth();
    };
    document.addEventListener("visibilitychange", onVisibility);

    return () => {
      clearInterval(interval);
      document.removeEventListener("visibilitychange", onVisibility);
    };
  }, []);

  async function setupFCM() {
    try {
      const registration = await navigator.serviceWorker.register("/firebase-messaging-sw.js");
      const messaging = getMessaging(app);

      const fcmToken = await getToken(messaging, {
        vapidKey: "BGZ4Fo8rRhoTdStLGlCySDZOnAX4ekCA0e3HDWXL5uEi2kOnXynYjbaDbY15002phUrFqxBpPPFHgfH2VhrmFDU",
        serviceWorkerRegistration: registration,
      });

      if (fcmToken) {
        await setFCMToken(fcmToken, 2);
      }

      onMessage(messaging, (payload) => {
        const title = payload.notification?.title || payload.data?.title || "Sweet Home";
        const body = payload.notification?.body || payload.data?.body || "";
        setNotification({ title, body });
        setTimeout(() => setNotification(null), 5000);
      });
    } catch (err) {
      console.error("[FCM] Setup error:", err);
    }
  }

  async function handleEnable() {
    setShowPrompt(false);

    // This MUST be synchronous from a user gesture
    const permission = await Notification.requestPermission();
    console.log("[FCM] Permission result:", permission);

    if (permission === "granted") {
      await setupFCM();
    }
  }

  return (
    <>
      {showPrompt && (
        <div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 bg-white rounded-xl shadow-2xl border border-gray-200 p-4 z-[9999]">
          <div className="flex items-start gap-3">
            <div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center flex-shrink-0">
              <span className="text-xl">🔔</span>
            </div>
            <div className="flex-1 min-w-0">
              <p className="font-bold text-gray-900 text-sm">تفعيل الإشعارات</p>
              <p className="text-gray-600 text-sm mt-0.5">اسمح بالإشعارات للبقاء على اطلاع بحجوزاتك وعروضنا.</p>
              <div className="flex gap-2 mt-3">
                <button
                  onClick={handleEnable}
                  className="px-4 py-1.5 bg-amber-500 text-white text-sm font-medium rounded-lg hover:bg-amber-600 transition-colors"
                >
                  تفعيل
                </button>
                <button
                  onClick={() => setShowPrompt(false)}
                  className="px-4 py-1.5 text-gray-500 text-sm hover:text-gray-700 transition-colors"
                >
                  لاحقاً
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {notification && (
        <div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 bg-white rounded-xl shadow-2xl border border-gray-200 p-4 z-[9999] animate-slide-up">
          <div className="flex items-start gap-3">
            <div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center flex-shrink-0">
              <span className="text-xl">🏠</span>
            </div>
            <div className="flex-1 min-w-0">
              <p className="font-bold text-gray-900 text-sm">{notification.title}</p>
              <p className="text-gray-600 text-sm mt-0.5">{notification.body}</p>
            </div>
            <button
              onClick={() => setNotification(null)}
              className="text-gray-400 hover:text-gray-600 flex-shrink-0"
            >
              ✕
            </button>
          </div>
        </div>
      )}
    </>
  );
}
