import { useCallback, useEffect, useState } from 'react';
import { ChatHistoryRestoreTarget, WorkspacePreferences } from '../types/terminal';

const STORAGE_KEY = 'workspace_preferences';
const VALID_RESTORE_TARGETS = new Set<ChatHistoryRestoreTarget>(['activeTab', 'newTab']);

const DEFAULT_PREFERENCES: WorkspacePreferences = {
  chatHistoryRestoreTarget: 'activeTab',
};

const deserializePreferences = (raw: Record<string, unknown>): WorkspacePreferences => {
  const prefs = { ...DEFAULT_PREFERENCES };

  if (
    typeof raw.chatHistoryRestoreTarget === 'string' &&
    VALID_RESTORE_TARGETS.has(raw.chatHistoryRestoreTarget as ChatHistoryRestoreTarget)
  ) {
    prefs.chatHistoryRestoreTarget = raw.chatHistoryRestoreTarget as ChatHistoryRestoreTarget;
  }

  return prefs;
};

export const useWorkspacePreferences = () => {
  const [preferences, setPreferences] = useState<WorkspacePreferences>(DEFAULT_PREFERENCES);
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        const parsed = JSON.parse(stored);
        if (parsed && typeof parsed === 'object') {
          setPreferences(deserializePreferences(parsed as Record<string, unknown>));
        }
      }
    } catch (error) {
      console.error('Failed to load workspace preferences from localStorage:', error);
    } finally {
      setIsLoaded(true);
    }
  }, []);

  useEffect(() => {
    if (!isLoaded) return;

    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(preferences));
    } catch (error) {
      console.error('Failed to save workspace preferences to localStorage:', error);
    }
  }, [preferences, isLoaded]);

  const updatePreferences = useCallback((patch: Partial<WorkspacePreferences>) => {
    setPreferences((prev) => ({ ...prev, ...patch }));
  }, []);

  return {
    preferences,
    updatePreferences,
    isLoaded,
  };
};
