"use client";

import { useEffect } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCurrentUser } from "./CurrentUserContext";

const SYNC_KEY = "sfs:last-global-auto-sync";
const FULL_SYNC_KEY = "sfs:last-full-auto-sync";
const FULL_SYNC_INTERVAL_MS = 6 * 60 * 60 * 1000;
const FULL_SYNC_RETRY_MS = 30 * 60 * 1000;
const DEFAULT_SYNC_INTERVAL_MS = 30_000;
const ORDER_SYNC_INTERVAL_MS = 10_000;
const REFRESH_INTERVAL_MS = 60_000;
const LIVE_ORDER_REFRESH_INTERVAL_MS = 10_000;
const BACKGROUND_SYNC_NAVIGATION_GRACE_MS = 5_000;
const REFRESH_ROUTES = ["/dashboard", "/orders", "/products", "/stock", "/reports", "/finance", "/optimizer", "/tokens"];
const LIVE_ORDER_ROUTES = ["/dashboard", "/orders"];

let inFlight = false;
let lastRefreshAt = 0;
let lastStartedAt = 0;

function shouldRefresh(pathname: string) {
  return REFRESH_ROUTES.some((route) => pathname === route || pathname.startsWith(`${route}/`));
}

function shouldLiveRefresh(pathname: string) {
  return LIVE_ORDER_ROUTES.some((route) => pathname === route || pathname.startsWith(`${route}/`));
}

function lastSyncAge() {
  const value = Number(window.localStorage.getItem(SYNC_KEY) || "0");
  const persistedAge = Number.isFinite(value) ? Date.now() - value : Number.POSITIVE_INFINITY;
  const startedAge = lastStartedAt ? Date.now() - lastStartedAt : Number.POSITIVE_INFINITY;
  return Math.min(persistedAge, startedAge);
}

export default function GlobalAutoSync() {
  const router = useRouter();
  const currentUser = useCurrentUser();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const selectedShopId = searchParams.get("shop_id");
  const fullSyncKey = `${FULL_SYNC_KEY}:${currentUser?.id || "anonymous"}`;

  useEffect(() => {
    if (!shouldRefresh(pathname) || (currentUser?.role === "super_admin" && (!selectedShopId || selectedShopId === "all"))) return;

    let stopped = false;
    let timer: number | null = null;
    const orderRoute = shouldLiveRefresh(pathname);
    const syncIntervalMs = orderRoute ? ORDER_SYNC_INTERVAL_MS : DEFAULT_SYNC_INTERVAL_MS;

    async function run() {
      if (stopped || document.hidden || inFlight || lastSyncAge() < syncIntervalMs) return;
      const lastFullSync = Number(window.localStorage.getItem(fullSyncKey) || "0");
      const needsFullSync = !orderRoute && (!Number.isFinite(lastFullSync) || Date.now() - lastFullSync > FULL_SYNC_INTERVAL_MS);
      inFlight = true;
      lastStartedAt = Date.now();
      window.localStorage.setItem(SYNC_KEY, String(lastStartedAt));
      // Tandai upaya sebelum request. Tab lain tidak perlu mengulang full sync
      // saat request pertama masih berjalan atau timeout.
      if (needsFullSync) {
        window.localStorage.setItem(fullSyncKey, String(Date.now() - FULL_SYNC_INTERVAL_MS + FULL_SYNC_RETRY_MS));
      }
      try {
        const res = await fetch("/api/shopee/dashboard/auto-sync", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            mode: orderRoute ? "orders" : needsFullSync ? "full" : "live",
            ...(!needsFullSync && selectedShopId && selectedShopId !== "all" ? { shopId: selectedShopId } : {}),
          }),
        });
        const json = (await res.json().catch(() => null)) as {
          ok?: boolean;
          success?: boolean;
          data?: { queued?: boolean; syncRunning?: boolean };
        } | null;
        if (res.ok && json?.ok) {
          if (needsFullSync && json.success && !json.data?.queued && !json.data?.syncRunning) {
            window.localStorage.setItem(fullSyncKey, String(Date.now()));
          }
          // Poll order dihitung dari waktu mulai supaya request empat toko yang
          // memakan beberapa detik tidak menambah jeda lagi setelah selesai.
          if (!orderRoute) window.localStorage.setItem(SYNC_KEY, String(Date.now()));
          // Tunggu sinkronisasi selesai sebelum render ulang. Refresh buta tiap
          // 10 detik sebelumnya menumpuk dengan request halaman saat navigasi.
          const refreshIntervalMs = orderRoute ? LIVE_ORDER_REFRESH_INTERVAL_MS : REFRESH_INTERVAL_MS;
          if (!stopped && !json.data?.queued && !json.data?.syncRunning && Date.now() - lastRefreshAt > refreshIntervalMs) {
            lastRefreshAt = Date.now();
            router.refresh();
          }
        }
      } catch {
        // Auto-sync tidak boleh mengganggu operator; error tersimpan di API log server.
      } finally {
        inFlight = false;
      }
    }

    timer = window.setTimeout(() => {
      void run();
    }, orderRoute ? 700 : BACKGROUND_SYNC_NAVIGATION_GRACE_MS);
    const interval = window.setInterval(() => {
      void run();
    }, syncIntervalMs);
    const onVisible = () => {
      if (!document.hidden) void run();
    };
    const onFocus = () => {
      void run();
    };
    window.addEventListener("focus", onFocus);
    document.addEventListener("visibilitychange", onVisible);

    return () => {
      stopped = true;
      if (timer !== null) window.clearTimeout(timer);
      window.clearInterval(interval);
      window.removeEventListener("focus", onFocus);
      document.removeEventListener("visibilitychange", onVisible);
    };
  }, [currentUser?.role, fullSyncKey, pathname, router, selectedShopId]);

  return null;
}
