import { useEffect } from "react";
import {
  PushNotifications,
  Token,
  PushNotificationSchema,
  ActionPerformed,
} from "@capacitor/push-notifications";
import { useIonRouter, isPlatform } from "@ionic/react";
import axios from "axios";
import { LocalNotifications } from "@capacitor/local-notifications";

const usePushNotifications = (userId?: string, apiURL?: string) => {
  const router = useIonRouter();

  useEffect(() => {
    if (!userId || !apiURL) return;

    const init = async () => {
      try {
        /* ------------------ 1️⃣ PERMISSIONS ------------------ */
        let permStatus = await PushNotifications.checkPermissions();

        if (permStatus.receive === "prompt") {
          permStatus = await PushNotifications.requestPermissions();
        }

        if (permStatus.receive !== "granted") {
          console.warn("❌ Push permission not granted");
          return;
        }

        /* ------------------ 2️⃣ REGISTER ------------------ */
        await PushNotifications.register();

        /* ------------------ 3️⃣ ANDROID CHANNEL ------------------ */
        if (isPlatform("android")) {
          await LocalNotifications.createChannel({
            id: "default",
            name: "General Notifications",
            description: "General app notifications",
            importance: 5,
            visibility: 1,
            sound: "default",
          });
        }

        /* ------------------ 4️⃣ TOKEN ------------------ */
        PushNotifications.addListener(
          "registration",
          async (token: Token) => {
            console.log("✅ FCM Token:", token.value);

            try {
              const res = await axios.post(
                apiURL,
                new URLSearchParams({
                  action: "register_notif_token",
                  user_id: userId,
                  token: token.value,
                }),
                {
                  headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                  },
                }
              );

              console.log("✅ Token saved:", res.data);
            } catch (err) {
              console.error("❌ Failed to save token:", err);
            }
          }
        );

        /* ------------------ 5️⃣ TOKEN ERROR ------------------ */
        PushNotifications.addListener("registrationError", (err) => {
          console.error("❌ Registration error:", err);
        });

        /* ------------------ 6️⃣ FOREGROUND HANDLING ------------------ */
        PushNotifications.addListener(
          "pushNotificationReceived",
          async (notification: PushNotificationSchema) => {
            console.log("📩 Foreground push:", notification);

            // 🔔 Manually show notification
            await LocalNotifications.schedule({
              notifications: [
                {
                  title: notification.title ?? "Notification",
                  body: notification.body ?? "",
                  id: Date.now(),
                  channelId: "default",
                  extra: notification.data,
                },
              ],
            });
          }
        );

        /* ------------------ 7️⃣ TAP HANDLER ------------------ */
        PushNotifications.addListener(
          "pushNotificationActionPerformed",
          (action: ActionPerformed) => {
            console.log("🔗 Notification tapped:", action);

            const route =
              action.notification.data?.route ||
               "/home";

            router.push(route, "forward");
          }
        );
      } catch (err) {
        console.error("❌ Push init error:", err);
      }
    };

    init();
  }, [userId, apiURL]);
};

export default usePushNotifications;
