"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 < 20) ? "light" : "dark";
}

function applyTheme(nextTheme: "light" | "dark") {
  const root = document.documentElement;
  root.classList.remove("light", "dark");
  root.classList.add(nextTheme);
  root.setAttribute("data-theme", nextTheme === "dark" ? "moon" : "sun");
}

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);
    applyTheme(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) => {
      const next = e.matches ? "dark" : "light";
      setTheme(next);
      applyTheme(next);
    };
    mediaQuery.addEventListener("change", handler);
    return () => mediaQuery.removeEventListener("change", handler);
  }, [mode]);

  // Update every 5 min when in time mode
  useEffect(() => {
    if (mode !== "time") return;
    const interval = setInterval(() => {
      const next = getTimeOfDayTheme();
      setTheme(next);
      applyTheme(next);
    }, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, [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);
}
