import { useCallback, useEffect, useState } from 'react';
import { useTheme } from '../../../contexts/ThemeContext';
import {
  CODE_EDITOR_DEFAULTS,
  CODE_EDITOR_SETTINGS_CHANGED_EVENT,
  CODE_EDITOR_STORAGE_KEYS,
} from '../constants/settings';

const readBoolean = (storageKey: string, defaultValue: boolean, falseValue = 'false') => {
  const value = localStorage.getItem(storageKey);
  if (value === null) {
    return defaultValue;
  }

  return value !== falseValue;
};

const readWordWrap = () => {
  return localStorage.getItem(CODE_EDITOR_STORAGE_KEYS.wordWrap) === 'true';
};

const readFontSize = () => {
  const stored = localStorage.getItem(CODE_EDITOR_STORAGE_KEYS.fontSize);
  return Number(stored ?? CODE_EDITOR_DEFAULTS.fontSize);
};

type ThemeContextValue = { isDarkMode: boolean; toggleDarkMode: () => void };

export const useCodeEditorSettings = () => {
  // Editor theme mirrors the app theme — one source of truth prevents the editor
  // from rendering dark after the user switches the app to light mode.
  const { isDarkMode, toggleDarkMode } = useTheme() as ThemeContextValue;

  const [wordWrap, setWordWrap] = useState(readWordWrap);
  const [minimapEnabled, setMinimapEnabled] = useState(() => (
    readBoolean(CODE_EDITOR_STORAGE_KEYS.showMinimap, CODE_EDITOR_DEFAULTS.minimapEnabled)
  ));
  const [showLineNumbers, setShowLineNumbers] = useState(() => (
    readBoolean(CODE_EDITOR_STORAGE_KEYS.lineNumbers, CODE_EDITOR_DEFAULTS.showLineNumbers)
  ));
  const [fontSize, setFontSize] = useState(readFontSize);

  // Mirror app theme into the legacy codeEditorTheme key so any remaining
  // localStorage readers stay in sync.
  useEffect(() => {
    localStorage.setItem(CODE_EDITOR_STORAGE_KEYS.theme, isDarkMode ? 'dark' : 'light');
  }, [isDarkMode]);

  useEffect(() => {
    localStorage.setItem(CODE_EDITOR_STORAGE_KEYS.wordWrap, String(wordWrap));
  }, [wordWrap]);

  useEffect(() => {
    const refreshFromStorage = () => {
      setWordWrap(readWordWrap());
      setMinimapEnabled(readBoolean(CODE_EDITOR_STORAGE_KEYS.showMinimap, CODE_EDITOR_DEFAULTS.minimapEnabled));
      setShowLineNumbers(readBoolean(CODE_EDITOR_STORAGE_KEYS.lineNumbers, CODE_EDITOR_DEFAULTS.showLineNumbers));
      setFontSize(readFontSize());
    };

    window.addEventListener('storage', refreshFromStorage);
    window.addEventListener(CODE_EDITOR_SETTINGS_CHANGED_EVENT, refreshFromStorage);

    return () => {
      window.removeEventListener('storage', refreshFromStorage);
      window.removeEventListener(CODE_EDITOR_SETTINGS_CHANGED_EVENT, refreshFromStorage);
    };
  }, []);

  const setIsDarkMode = useCallback((next: boolean) => {
    if (next !== isDarkMode) {
      toggleDarkMode();
    }
  }, [isDarkMode, toggleDarkMode]);

  return {
    isDarkMode,
    setIsDarkMode,
    wordWrap,
    setWordWrap,
    minimapEnabled,
    setMinimapEnabled,
    showLineNumbers,
    setShowLineNumbers,
    fontSize,
    setFontSize,
  };
};
