import { useCallback } from 'react';

const STORAGE_PREFIX = 'estoppel_form_data_v1_';

export function useEstoppelFormData() {
  const getStorageKey = (associationId, unitId) => {
    if (!associationId || !unitId) return null;
    return `${STORAGE_PREFIX}${associationId}_${unitId}`;
  };

  const saveFormData = useCallback((associationId, unitId, data) => {
    const key = getStorageKey(associationId, unitId);
    if (!key || !data) return false;
    try {
      localStorage.setItem(key, JSON.stringify({ ...data, _savedAt: new Date().toISOString() }));
      return true;
    } catch (error) {
      console.error('Failed to save estoppel form data:', error);
      return false;
    }
  }, []);

  const loadFormData = useCallback((associationId, unitId) => {
    const key = getStorageKey(associationId, unitId);
    if (!key) return null;
    try {
      const item = localStorage.getItem(key);
      if (!item) return null;
      return JSON.parse(item);
    } catch (error) {
      console.error('Failed to load estoppel form data:', error);
      return null;
    }
  }, []);

  const clearFormData = useCallback((associationId, unitId) => {
    const key = getStorageKey(associationId, unitId);
    if (key) localStorage.removeItem(key);
  }, []);

  const hasSavedData = useCallback((associationId, unitId) => {
    const key = getStorageKey(associationId, unitId);
    if (!key) return false;
    return !!localStorage.getItem(key);
  }, []);

  return { saveFormData, loadFormData, clearFormData, hasSavedData };
}
