import { createContext, FC, ReactNode, useContext, useEffect, useState } from "react";
import { logcat } from "../lib/logcatService";
import { defaultSettings, readConfigFile, SettingsType, writeConfigFile } from "../lib/settings";

// settings context
type SettingsContextProps = {
  settings: SettingsType;
  settingsLoading: boolean;
  updateSettings: (updates: SettingsType) => void;
  resetSettings: () => void;
};

const SettingsContext = createContext<SettingsContextProps | undefined>(undefined);

export const SettingsProvider: FC<{ children: ReactNode }> = ({ children }) => {
  logcat.log("Initializing settings...", "INFO");

  // states
  const [settings, setSettings] = useState<SettingsType>(defaultSettings);
  const [settingsLoading, setSettingsLoading] = useState<boolean>(true);

  const fetchSettings = async () => {
    try {
      const existingSettings = await readConfigFile();
      setSettings(existingSettings);
    } catch (error) {
      logcat.log(`Failed to load settings: ${error}`, "ERROR");
    } finally {
      setSettingsLoading(false);
    }
  };

  const updateSettings = async (newSettings: SettingsType) => {
    try {
      await writeConfigFile(newSettings);
      setSettings(newSettings);
      logcat.log("Settings updated successfully", "INFO");
    } catch (error) {
      logcat.log(`Failed to update settings: ${error}`, "ERROR");
    }
  };

  // set settings state to default values
  // and write default values to the settings file
  const resetSettings = async () => {
    try {
      await writeConfigFile(defaultSettings);
      setSettings(defaultSettings);
      logcat.log("Settings reset successfully", "INFO");
    } catch (error) {
      logcat.log(`Failed to reset settings: ${error}`, "ERROR");
    }
  };

  // fetch user settings from local on first load every time
  useEffect(() => {
    fetchSettings();
  }, []);

  return (
    <SettingsContext.Provider
      value={{
        settings,
        settingsLoading,
        updateSettings,
        resetSettings,
      }}
    >
      {children}
    </SettingsContext.Provider>
  );
};

export const useSettings = () => {
  const context = useContext(SettingsContext);
  if (context === undefined) {
    throw new Error("Please use useSettings only within a SettingsProvider");
  }
  return context;
};
