import { createContext, useContext, useEffect, useState, ReactNode } from "react";

export interface SearchEngine {
  id: string;
  name: string;
  enabled: boolean;
}

const DEFAULT_ENGINES: SearchEngine[] = [
  { id: "google", name: "Google", enabled: true },
  { id: "duckduckgo", name: "DuckDuckGo", enabled: true },
  { id: "brave", name: "Brave", enabled: true },
  { id: "bing", name: "Bing", enabled: false },
  { id: "wikipedia", name: "Wikipedia", enabled: true },
];

type Theme = "light" | "dark";

interface PreferencesState {
  theme: Theme;
  engines: SearchEngine[];
  setTheme: (t: Theme) => void;
  toggleEngine: (id: string) => void;
}

const PreferencesContext = createContext<PreferencesState | null>(null);

function loadFromStorage<T>(key: string, fallback: T): T {
  try {
    const raw = localStorage.getItem(key);
    return raw ? JSON.parse(raw) : fallback;
  } catch {
    return fallback;
  }
}

export function PreferencesProvider({ children }: { children: ReactNode }) {
  const [theme, setThemeState] = useState<Theme>(() => loadFromStorage("kafka-theme", "light"));
  const [engines, setEngines] = useState<SearchEngine[]>(() => loadFromStorage("kafka-engines", DEFAULT_ENGINES));

  useEffect(() => {
    document.documentElement.classList.toggle("dark", theme === "dark");
    localStorage.setItem("kafka-theme", JSON.stringify(theme));
  }, [theme]);

  useEffect(() => {
    localStorage.setItem("kafka-engines", JSON.stringify(engines));
  }, [engines]);

  const setTheme = (t: Theme) => setThemeState(t);

  const toggleEngine = (id: string) => {
    setEngines((prev) => prev.map((e) => (e.id === id ? { ...e, enabled: !e.enabled } : e)));
  };

  return (
    <PreferencesContext.Provider value={{ theme, engines, setTheme, toggleEngine }}>
      {children}
    </PreferencesContext.Provider>
  );
}

export function usePreferences() {
  const ctx = useContext(PreferencesContext);
  if (!ctx) throw new Error("usePreferences must be used within PreferencesProvider");
  return ctx;
}
