"use client";

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

type Theme = "light" | "dark" | "system" | "time";

interface ThemeContextType {
  theme: "light" | "dark";
  mode: Theme;
  toggle: () => void;
  setMode: (mode: Theme) => void;
}

const ThemeContext = createContext<ThemeContextType>({
  theme: "light",
  mode: "light",
  toggle: () => {},
  setMode: () => {},
});

function getSystemTheme(): "light" | "dark" {
  if (typeof window === "undefined") return "light";
  return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}

function getTimeOfDayTheme(): "light" | "dark" {
  const hour = new Date().getHours();
  return (hour >= 6 && hour < 18) ? "light" : "dark";
}

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [mode, setModeState] = useState<Theme>("light");
  const [theme, setTheme] = useState<"light" | "dark">("light");
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    const saved = localStorage.getItem("tia_theme") as Theme | null;
    const initialMode = saved || "system";
    setModeState(initialMode);
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted) return;

    let nextTheme: "light" | "dark";
    if (mode === "system") {
      nextTheme = getSystemTheme();
    } else if (mode === "time") {
      nextTheme = getTimeOfDayTheme();
    } else {
      nextTheme = mode as "light" | "dark";
    }

    setTheme(nextTheme);
    document.documentElement.classList.remove("light", "dark");
    document.documentElement.classList.add(nextTheme);
  }, [mode, mounted]);

  // Listen for system theme changes
  useEffect(() => {
    if (mode !== "system") return;
    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
    const handler = (e: MediaQueryListEvent) => {
      setTheme(e.matches ? "dark" : "light");
      document.documentElement.classList.remove("light", "dark");
      document.documentElement.classList.add(e.matches ? "dark" : "light");
    };
    mediaQuery.addEventListener("change", handler);
    return () => mediaQuery.removeEventListener("change", handler);
  }, [mode]);

  const setMode = (newMode: Theme) => {
    setModeState(newMode);
    localStorage.setItem("tia_theme", newMode);
  };

  const toggle = () => {
    setMode(theme === "light" ? "dark" : "light");
  };

  return (
    <ThemeContext.Provider value={{ theme, mode, toggle, setMode }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useTheme() {
  return useContext(ThemeContext);
}