"use client";

import Navbar from "@/views/shared/Navbar";
import Footer from "@/views/shared/Footer";
import { HeroUIProvider } from "@heroui/react";
import { ToastContainer, toast, ToastOptions } from "react-toastify";
import { useLocale } from "next-intl";
import { ReactNode, createContext, useContext, useEffect } from "react";
import "react-toastify/dist/ReactToastify.css";
import type { FooterLink, GeneralSettingsMap } from "@/lib/api";
import {
  requestFcmToken,
  setStoredFcmToken,
  subscribeToForegroundMessages,
} from "@/lib/firebase/messaging";
import { emitNewNotification } from "@/lib/notificationEvents";
import { checkAndClearSessionOnVersionUpdate } from "@/lib/version-check";
import { ensureArchivedAccountAxiosInterceptors } from "@/lib/ensure-archived-account-axios";
import ArchivedAccountModalHost from "@/components/auth/ArchivedAccountModalHost";

const ToastContext = createContext({
  success: (msg: string, options?: ToastOptions) => { },
  error: (msg: string, options?: ToastOptions) => { },
  info: (msg: string, options?: ToastOptions) => { },
  warning: (msg: string, options?: ToastOptions) => { },
});

type NumberContextType = {
  toLatinDigits: (value: string | number | null | undefined) => string;
};

const NumberContext = createContext<NumberContextType>({
  toLatinDigits: (value) => {
    if (value === null || value === undefined) return "";
    return String(value);
  },
});

export const useAppToast = () => useContext(ToastContext);
export const useNumberFormatter = () => useContext(NumberContext);

const toLatinDigits = (value: string | number | null | undefined): string => {
  if (value === null || value === undefined) return "";
  const str = String(value);
  // Arabic-Indic:   ٠١٢٣٤٥٦٧٨٩  (U+0660–U+0669)
  // Eastern Arabic: ۰۱۲۳۴۵۶۷۸۹  (U+06F0–U+06F9)
  return str.replace(/[\u0660-\u0669\u06F0-\u06F9]/g, (d) => {
    const code = d.charCodeAt(0);
    if (code >= 0x0660 && code <= 0x0669) {
      return String(code - 0x0660);
    }
    if (code >= 0x06f0 && code <= 0x06f9) {
      return String(code - 0x06f0);
    }
    return d;
  });
};

export function Providers({
  children,
  footerSettings,
  footerLinks,
}: {
  children: ReactNode;
  footerSettings?: GeneralSettingsMap;
  footerLinks?: FooterLink[];
}) {
  const locale = useLocale();
  const safeFooterSettings = footerSettings ?? {};
  const safeFooterLinks = footerLinks ?? [];

  useEffect(() => {
    let detachForegroundListener = () => { };

    const setupMessaging = async () => {
      console.log("[firebase] Setup messaging start");
      const { token, reason, deviceType } = await requestFcmToken();

      if (token) {
        console.log(
          "[firebase] FCM registration token",
          token,
          "| device:",
          deviceType,
        );
        setStoredFcmToken(token, deviceType);
      } else {
        console.info(
          `[firebase] FCM token unavailable (${reason}) on ${deviceType}.`,
        );
      }

      const messageHandler = (payload: any) => {
        console.log("[firebase] Foreground FCM message", payload);

        const title =
          (payload.notification && payload.notification.title) ||
          "New notification from Ataya";
        const body = payload.notification && payload.notification.body;
        const message = body ? `${title}: ${body}` : title;

        // Show toast notification
        toast.info(message, { rtl: locale === "ar" });

        // Emit event so NotificationDropdown (and others) can refresh
        emitNewNotification({
          title,
          body: body || undefined,
          data: payload.data,
          timestamp: new Date().toISOString(),
        });
      };

      detachForegroundListener = subscribeToForegroundMessages(messageHandler);
    };

    setupMessaging().catch((error) =>
      console.error("[firebase] Messaging setup failed", error),
    );

    return () => detachForegroundListener();
  }, [locale]);

  useEffect(() => {
    checkAndClearSessionOnVersionUpdate();
  }, []);

  useEffect(() => {
    ensureArchivedAccountAxiosInterceptors();
  }, []);

  const toastValue = {
    success: (msg: string, options?: ToastOptions) =>
      toast.success(msg, { rtl: locale === "ar", ...options }),
    error: (msg: string, options?: ToastOptions) =>
      toast.error(msg, { rtl: locale === "ar", ...options }),
    info: (msg: string, options?: ToastOptions) =>
      toast.info(msg, { rtl: locale === "ar", ...options }),
    warning: (msg: string, options?: ToastOptions) =>
      toast.warning(msg, { rtl: locale === "ar", ...options }),
  };

  return (
    <HeroUIProvider>
      <ToastContext.Provider value={toastValue}>
        <NumberContext.Provider value={{ toLatinDigits }}>
          <div className="min-h-screen flex flex-col">
            <Navbar />
            <main className="flex-1 max-w-full overflow-x-hidden overflow-y-clip">
              {children}
            </main>
            <Footer
              footerSettings={safeFooterSettings}
              footerLinks={safeFooterLinks}
            />
          </div>
          <ToastContainer
            rtl={locale === "ar"}
            position={locale === "ar" ? "top-right" : "top-left"}
            theme="colored"
            limit={5}
            newestOnTop
            pauseOnHover
            closeOnClick
            autoClose={4500}
            hideProgressBar={false}
            className="toast-container-custom"
          />
          <ArchivedAccountModalHost />
        </NumberContext.Provider>
      </ToastContext.Provider>
    </HeroUIProvider>
  );
}
