import { useState, useEffect, useCallback } from 'react';

interface WizardDraft<T> {
  data: T;
  timestamp: number;
  currentStep: number;
}

interface UseWizardDraftOptions {
  key: string; // Unique key for this wizard type
  ttl?: number; // Time to live in milliseconds (default: 7 days)
  autoSaveInterval?: number; // Auto-save interval in milliseconds (default: 30 seconds)
}

export function useWizardDraft<T>(options: UseWizardDraftOptions) {
  const { key, ttl = 7 * 24 * 60 * 60 * 1000, autoSaveInterval = 30000 } = options;
  const storageKey = `wizard_draft_${key}`;

  const [draftData, setDraftData] = useState<T | null>(null);
  const [draftStep, setDraftStep] = useState<number>(0);
  const [hasDraft, setHasDraft] = useState(false);
  const [lastSaved, setLastSaved] = useState<Date | null>(null);

  // Load draft on mount
  useEffect(() => {
    try {
      const stored = localStorage.getItem(storageKey);
      if (stored) {
        const draft: WizardDraft<T> = JSON.parse(stored);

        // Check if draft is still valid (not expired)
        const now = Date.now();
        if (now - draft.timestamp < ttl) {
          setDraftData(draft.data);
          setDraftStep(draft.currentStep);
          setHasDraft(true);
          setLastSaved(new Date(draft.timestamp));
        } else {
          // Draft expired, clear it
          localStorage.removeItem(storageKey);
        }
      }
    } catch (error) {
      console.error('Error loading wizard draft:', error);
      localStorage.removeItem(storageKey);
    }
  }, [storageKey, ttl]);

  // Save draft
  const saveDraft = useCallback(
    (data: T, currentStep: number) => {
      try {
        const draft: WizardDraft<T> = {
          data,
          timestamp: Date.now(),
          currentStep
        };
        localStorage.setItem(storageKey, JSON.stringify(draft));
        setLastSaved(new Date());
        setHasDraft(true);
      } catch (error) {
        console.error('Error saving wizard draft:', error);
      }
    },
    [storageKey]
  );

  // Clear draft
  const clearDraft = useCallback(() => {
    try {
      localStorage.removeItem(storageKey);
      setDraftData(null);
      setDraftStep(0);
      setHasDraft(false);
      setLastSaved(null);
    } catch (error) {
      console.error('Error clearing wizard draft:', error);
    }
  }, [storageKey]);

  // Load draft data
  const loadDraft = useCallback(() => {
    return { data: draftData, step: draftStep };
  }, [draftData, draftStep]);

  // Dismiss draft (clear without loading)
  const dismissDraft = useCallback(() => {
    clearDraft();
  }, [clearDraft]);

  return {
    // State
    hasDraft,
    lastSaved,

    // Actions
    saveDraft,
    loadDraft,
    clearDraft,
    dismissDraft
  };
}

// Format time ago
export function formatTimeAgo(date: Date): string {
  const now = new Date();
  const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  if (seconds < 60) return 'hace un momento';
  if (seconds < 3600) return `hace ${Math.floor(seconds / 60)} minutos`;
  if (seconds < 86400) return `hace ${Math.floor(seconds / 3600)} horas`;
  return `hace ${Math.floor(seconds / 86400)} días`;
}
