"use client";

import { useEffect, useState, useRef } from "react";
import { performPushSync, performPullSync, checkConnectionStatus } from "@/app/actions/sync";
import { processAutomatedNotifications } from "@/app/actions/notifications";
import { RefreshCcwIcon } from "lucide-react";

export function SyncWorker({ setSyncStatus }: { setSyncStatus: (st: { configured: boolean, online: boolean } | null) => void }) {
  const lastSyncDateRef = useRef<string | null>(null);
  const lastFastCheckRef = useRef<string>(new Date().toISOString());
  const [isSyncing, setIsSyncing] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") return;

    /** Fast-check: Ask the online server if any new W- orders arrived since lastFastCheck */
    const fastCheckNewOrders = async (baseUrl: string): Promise<boolean> => {
      try {
        const url = `${baseUrl}/api/sync/new-orders/check?since=${encodeURIComponent(lastFastCheckRef.current)}`;
        const res = await fetch(url, { signal: AbortSignal.timeout(3000) });
        if (!res.ok) return false;
        const data = await res.json();
        // Update the fast-check cursor so next time we look only at newer orders
        lastFastCheckRef.current = data.checkedAt || new Date().toISOString();
        return data.hasNew === true;
      } catch {
        return false; // If check fails, do a full pull to be safe
      }
    };

    const doSync = async () => {
      const conn = await checkConnectionStatus();
      setSyncStatus(conn);
      if (!conn.configured || !conn.online) return;

      setIsSyncing(true);
      try {
        // 1. Push local changes to server
        const pushRes = await performPushSync();
        if (pushRes?.success && pushRes.count && pushRes.count > 0) {
          console.log(`[SYNC] Pushed ${pushRes.count} records to server.`);
        }

        // 2. Smart pull: only do a full pull when needed
        //    - Always pull on first run (lastSyncDateRef is null)
        //    - After that, first do a lightweight fast-check
        let shouldPull = !lastSyncDateRef.current; // always pull on first run

        if (!shouldPull) {
          const baseUrl = (conn as any).baseUrl;
          if (baseUrl) {
            const hasNew = await fastCheckNewOrders(baseUrl);
            if (hasNew) {
              console.log("[SYNC] Fast-check: new online orders detected → starting full pull.");
              shouldPull = true;
            }
          } else {
            // No URL in settings, fall back to periodic pull every ~60s
            const lastSync = lastSyncDateRef.current ? new Date(lastSyncDateRef.current) : null;
            if (!lastSync || Date.now() - lastSync.getTime() > 60_000) {
              shouldPull = true;
            }
          }
        }

        if (shouldPull) {
          const pullRes = await performPullSync(lastSyncDateRef.current);
          if (pullRes?.success) {
            if (pullRes.count && Number(pullRes.count) > 0) {
              console.log(`[SYNC] Pulled ${pullRes.count} records from server.`);
            }
            if (pullRes.timestamp) {
              lastSyncDateRef.current = pullRes.timestamp;
            }
          }
        }

        // 3. Process automated notifications
        await processAutomatedNotifications();

      } catch (e) {
        console.error("[SYNC] Background sync error", e);
      } finally {
        setTimeout(() => setIsSyncing(false), 2000);
      }
    };

    const initialTimeout = setTimeout(doSync, 2000);
    const interval = setInterval(doSync, 10000); // every 10 seconds

    return () => {
      clearTimeout(initialTimeout);
      clearInterval(interval);
    };
  }, [setSyncStatus]);

  if (!isSyncing) return null;

  return (
    <div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 flex items-center gap-2 z-50 pointer-events-none" style={{ WebkitAppRegion: 'no-drag' } as any}>
      <RefreshCcwIcon className="w-3 h-3 text-emerald-400 animate-spin" />
      <span className="text-[11px] text-emerald-400 font-bold tracking-wider pt-0.5">در حال همگام‌سازی...</span>
    </div>
  );
}
