
import { useEffect, useState } from "react";
import { UseFormReturn, DefaultValues, FieldValues } from "react-hook-form";

export function useFormPersistence<T extends FieldValues>(
  form: UseFormReturn<T>,
  storageKey: string | null,
  initialValues?: Partial<T>
) {
  const [isInitialized, setIsInitialized] = useState(false);

  // Load saved form data from localStorage
  useEffect(() => {
    if (!storageKey) {
      setIsInitialized(true);
      return;
    }
    try {
      const savedData = localStorage.getItem(storageKey);
      if (savedData) {
        const parsedData = JSON.parse(savedData);
        // Reset form with saved values merged with initial values
        // Use as DefaultValues<T> to satisfy TypeScript
        form.reset({ ...(initialValues || {}), ...parsedData } as DefaultValues<T>);
      } else if (initialValues) {
        // If no saved data but initial values exist, use them
        form.reset(initialValues as DefaultValues<T>);
      }
    } catch (error) {
      console.error("Error loading saved form data:", error);
      localStorage.removeItem(storageKey);
    }
    setIsInitialized(true);
  }, [storageKey, form, initialValues]);

  // Save form data to localStorage when values change
  useEffect(() => {
    if (!isInitialized || !storageKey) return;

    const subscription = form.watch((values) => {
      if (values && Object.keys(values).length > 0) {
        localStorage.setItem(storageKey, JSON.stringify(values));
      }
    });

    // Cleanup subscription
    return () => subscription.unsubscribe();
  }, [form, storageKey, isInitialized]);

  // Clear saved data when form is submitted or on demand
  const clearSavedData = () => {
    if (storageKey) localStorage.removeItem(storageKey);
  };

  return {
    clearSavedData,
  };
}
