import { useEffect, useRef } from 'react';
import { router } from '@inertiajs/react';
import type { PendingVisit } from '@inertiajs/core';
import {
  confirm,
  type ConfirmOptions,
} from '@rutatiina/ui/providers/confirm-provider';

type LeaveGuard = ConfirmOptions & {
  /** Read at the moment someone tries to leave, so it can use refs. */
  when: () => boolean;
  /** Visits that never count as leaving, on top of saves, prefetches and background reloads. */
  ignore?: (visit: PendingVisit) => boolean;
};

/**
 * Asks before someone leaves unsaved work. Links inside the application get the
 * themed confirmation; closing or reloading the tab can only get the browser's
 * own prompt, which no page is allowed to replace.
 */
export function useLeaveGuard(guard: LeaveGuard): void {
  const latest = useRef(guard);
  latest.current = guard;

  useEffect(() => {
    let asking = false;
    let bypass = false;

    const unload = (event: BeforeUnloadEvent) => {
      if (!latest.current.when()) return;
      event.preventDefault();
      event.returnValue = '';
    };
    window.addEventListener('beforeunload', unload);

    const stop = router.on('before', (event) => {
      const visit = event.detail.visit;
      const { when, ignore, ...options } = latest.current;
      // Submitting a form (POST, PUT, DELETE…) saves the work rather than leaving it.
      if (bypass || visit.method !== 'get' || visit.prefetch) return;
      if (ignore?.(visit) || !when()) return;
      // Topbar notification and message polling refreshes this screen without leaving it.
      if (
        visit.only.length > 0 &&
        visit.preserveState &&
        visit.url.pathname === window.location.pathname
      )
        return;

      event.preventDefault();
      if (asking) return;
      asking = true;
      void confirm(options).then((leave) => {
        asking = false;
        if (!leave) return;
        bypass = true;
        try {
          router.visit(visit.url.href, {
            method: visit.method,
            data: visit.data,
            replace: visit.replace,
            preserveState: visit.preserveState,
            preserveScroll: visit.preserveScroll,
            only: visit.only,
            except: visit.except,
            headers: visit.headers,
          });
        } finally {
          bypass = false;
        }
      });
    });

    return () => {
      window.removeEventListener('beforeunload', unload);
      stop();
    };
  }, []);
}
