import { useCallback, useEffect, useRef } from 'react';
import { PortfolioConfig } from '@/src/types/portfolio';

interface AutosaveEntry {
  timestamp: number;
  config: PortfolioConfig;
  isRestored?: boolean;
}

const MAX_ENTRIES = 15;
const STORAGE_KEY = (portfolioId: string) => `portfolio_autosave_${portfolioId}`;

export function useAutosave(config: PortfolioConfig | null, portfolioId: string, delay: number = 2000) {
  const timeoutRef = useRef<NodeJS.Timeout>();
  const lastSavedRef = useRef<string>();
  const historyRef = useRef<AutosaveEntry[]>([]);
  const isRestoringRef = useRef(false);

  useEffect(() => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY(portfolioId));
      if (stored) {
        historyRef.current = JSON.parse(stored);
      }
    } catch (error) {
      console.error('Error loading history:', error);
    }
  }, [portfolioId]);

  const saveToLocalStorage = useCallback(
    (configToSave: PortfolioConfig) => {
      try {
        if (isRestoringRef.current) {
          isRestoringRef.current = false;
          return;
        }

        const newEntry: AutosaveEntry = {
          timestamp: Date.now(),
          config: configToSave,
        };

        historyRef.current = [newEntry, ...historyRef.current].slice(0, MAX_ENTRIES);

        localStorage.setItem(STORAGE_KEY(portfolioId), JSON.stringify(historyRef.current));
      } catch (error) {
        console.error('Error saving to localStorage:', error);
      }
    },
    [portfolioId]
  );

  useEffect(() => {
    if (!config || !portfolioId) return;

    const configString = JSON.stringify(config);
    if (configString === lastSavedRef.current) {
      return;
    }

    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }

    timeoutRef.current = setTimeout(() => {
      saveToLocalStorage(config);
      lastSavedRef.current = configString;
    }, delay);

    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, [config, portfolioId, delay, saveToLocalStorage]);

  return {
    getHistory: useCallback(() => {
      return historyRef.current;
    }, []),

    restoreVersion: useCallback((timestamp: number) => {
      const entry = historyRef.current.find((e) => e.timestamp === timestamp);
      if (entry) {
        isRestoringRef.current = true;
        return entry.config;
      }
      return null;
    }, []),

    clearHistory: useCallback(() => {
      historyRef.current = [];
      localStorage.removeItem(STORAGE_KEY(portfolioId));
    }, [portfolioId]),
  };
}
