"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { themes, Theme, getTheme, applyThemeToCss } from "@/lib/themes";

interface ThemeContextType {
  theme: Theme;
  themeId: string;
  setTheme: (id: string) => Promise<void>;
  loading: boolean;
}

const ThemeContext = createContext<ThemeContextType>({
  theme: themes.food,
  themeId: "food",
  setTheme: async () => {},
  loading: true,
});

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setThemeState] = useState<Theme>(themes.food);
  const [themeId, setThemeId] = useState<string>("food");
  const [loading, setLoading] = useState(true);

  // Load theme on mount
  useEffect(() => {
    loadTheme();
  }, []);

  const loadTheme = async () => {
    try {
      const res = await fetch("/api/settings/theme");
      const data = await res.json();
      
      if (data.theme) {
        const loadedTheme = getTheme(data.theme);
        setThemeState(loadedTheme);
        setThemeId(data.theme);
        applyThemeToCss(loadedTheme);
      }
    } catch (error) {
      // Use default theme
      applyThemeToCss(themes.food);
    } finally {
      setLoading(false);
    }
  };

  const setTheme = async (id: string) => {
    try {
      const res = await fetch("/api/settings/theme", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ theme: id }),
      });

      if (res.ok) {
        const newTheme = getTheme(id);
        setThemeState(newTheme);
        setThemeId(id);
        applyThemeToCss(newTheme);
      }
    } catch (error) {
      console.error("Failed to set theme:", error);
    }
  };

  return (
    <ThemeContext.Provider value={{ theme, themeId, setTheme, loading }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useThemeContext() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error("useThemeContext must be used within a ThemeProvider");
  }
  return context;
}
