import { useState, useEffect } from 'react';
import { useSettingsPersistence, SettingsState } from './useSettingsPersistence';
import { useUnits } from '../../../core/units/UnitsContext';

const defaultSettings: SettingsState = {
  darkMode: false,
  unitSystem: 'imperial',
  notifications: {
    email: true,
    push: true,
    maintenance: true,
  },
};

export const useSettings = () => {
  const { loadSettings, saveSettings } = useSettingsPersistence();
  const { unitSystem: contextUnitSystem, setUnitSystem: setContextUnitSystem } = useUnits();
  const [settings, setSettings] = useState<SettingsState>(defaultSettings);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Load settings from localStorage on mount
  useEffect(() => {
    try {
      setIsLoading(true);
      setError(null);

      const savedSettings = loadSettings();
      if (savedSettings) {
        setSettings(savedSettings);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load settings');
    } finally {
      setIsLoading(false);
    }
  }, [loadSettings]);

  // Sync unitSystem from context (which may load from backend)
  useEffect(() => {
    if (contextUnitSystem && contextUnitSystem !== settings.unitSystem) {
      setSettings(prev => ({ ...prev, unitSystem: contextUnitSystem }));
    }
  }, [contextUnitSystem, settings.unitSystem]);

  const updateSetting = <K extends keyof SettingsState>(
    key: K,
    value: SettingsState[K]
  ) => {
    try {
      setError(null);
      const newSettings = { ...settings, [key]: value };
      setSettings(newSettings);
      saveSettings(newSettings);

      // Sync unitSystem changes to context (which syncs to backend)
      if (key === 'unitSystem' && typeof value === 'string') {
        setContextUnitSystem(value as 'imperial' | 'metric');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save settings');
    }
  };

  return {
    settings,
    updateSetting,
    isLoading,
    error,
  };
};

export type { SettingsState } from './useSettingsPersistence';