/**
 * useImportAutosave Hook
 *
 * Connects a component to the import session autosave system.
 * Registers a data getter and tracks changes to trigger autosaves.
 */

import { useEffect, useCallback, useRef } from 'react';
import { useImportSession } from '@/contexts/ImportSessionContext';
import type { ImportSessionData } from '@/types/importSession';

interface UseImportAutosaveOptions {
  /** Whether autosave is enabled for this component */
  enabled: boolean;
  /** Function that returns the current session data to save */
  getSessionData: () => ImportSessionData;
  /** Current step identifier */
  step: 'validation' | 'imageUpload';
}

/**
 * Hook to integrate a component with the import session autosave system.
 *
 * @example
 * ```tsx
 * const { markDirty } = useImportAutosave({
 *   enabled: true,
 *   step: 'validation',
 *   getSessionData: () => ({
 *     current_step: 'validation',
 *     data: rows,
 *     validation_state: { errors, upcStatus, generatedItemNumbers },
 *   }),
 * });
 *
 * // Call markDirty whenever data changes
 * const handleCellChange = (value) => {
 *   updateCell(value);
 *   markDirty();
 * };
 * ```
 */
export function useImportAutosave({
  enabled,
  getSessionData,
  step,
}: UseImportAutosaveOptions) {
  const {
    setDataGetter,
    setCurrentStep,
    markDirty: contextMarkDirty,
    isSaving,
    lastSaved,
    sessionId,
    sessionName,
  } = useImportSession();

  // Keep getSessionData ref updated to avoid stale closures
  const getSessionDataRef = useRef(getSessionData);
  useEffect(() => {
    getSessionDataRef.current = getSessionData;
  }, [getSessionData]);

  // Register the data getter with the context and trigger initial autosave
  useEffect(() => {
    if (enabled) {
      setDataGetter(() => getSessionDataRef.current());
      setCurrentStep(step);
      // Trigger initial autosave so the session is persisted immediately
      contextMarkDirty();
    }
  }, [enabled, setDataGetter, setCurrentStep, step, contextMarkDirty]);

  /**
   * Mark the session as dirty (has unsaved changes).
   * This triggers the debounced autosave in the context.
   */
  const markDirty = useCallback(() => {
    if (enabled) {
      contextMarkDirty();
    }
  }, [enabled, contextMarkDirty]);

  return {
    /** Call this when data changes to trigger autosave */
    markDirty,
    /** Whether a save operation is currently in progress */
    isSaving,
    /** Timestamp of last successful save */
    lastSaved,
    /** Current session ID (null if new/unsaved) */
    sessionId,
    /** Current session name (null if unnamed) */
    sessionName,
  };
}
