"use client";
import { SessionProvider } from "next-auth/react";
import React, { createContext, useContext, useEffect, useState } from "react";
import { I18nProvider } from "@/lib/i18n";

export type ThemeMode = "system" | "light" | "dark";

interface ThemeContextType {
  theme: ThemeMode;
  resolvedTheme: "light" | "dark";
  setTheme: (mode: ThemeMode) => void;
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType>({
  theme: "system",
  resolvedTheme: "light",
  setTheme: () => {},
  toggleTheme: () => {},
});

export const useTheme = () => useContext(ThemeContext);

function ThemeManager({ children }: { children: React.ReactNode }) {
  const [theme, setThemeState] = useState<ThemeMode>("system");
  const [resolvedTheme, setResolvedTheme] = useState<"light" | "dark">("light");

  const applyTheme = (mode: ThemeMode) => {
    let effective: "light" | "dark" = "light";
    if (mode === "system") {
      const isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
      effective = isDark ? "dark" : "light";
    } else {
      effective = mode;
    }
    setResolvedTheme(effective);
    document.documentElement.setAttribute("data-theme", effective);
  };

  useEffect(() => {
    const saved = localStorage.getItem("checkflow_theme") as ThemeMode | null;
    const initial = saved || "system";
    setThemeState(initial);
    applyTheme(initial);

    // Listen for system theme changes if set to system
    const media = window.matchMedia("(prefers-color-scheme: dark)");
    const listener = (e: MediaQueryListEvent) => {
      const current = (localStorage.getItem("checkflow_theme") as ThemeMode) || "system";
      if (current === "system") {
        const effective = e.matches ? "dark" : "light";
        setResolvedTheme(effective);
        document.documentElement.setAttribute("data-theme", effective);
      }
    };

    media.addEventListener("change", listener);

    // Register Service Worker
    if ("serviceWorker" in navigator) {
      navigator.serviceWorker.register("/sw.js").catch(console.error);
    }

    return () => media.removeEventListener("change", listener);
  }, []);

  const setTheme = (mode: ThemeMode) => {
    setThemeState(mode);
    localStorage.setItem("checkflow_theme", mode);
    applyTheme(mode);
  };

  // Cycles through: System -> Light -> Dark -> System
  const toggleTheme = () => {
    const sequence: ThemeMode[] = ["system", "light", "dark"];
    const nextIndex = (sequence.indexOf(theme) + 1) % sequence.length;
    setTheme(sequence[nextIndex]);
  };

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

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <SessionProvider>
      <I18nProvider>
        <ThemeManager>{children}</ThemeManager>
      </I18nProvider>
    </SessionProvider>
  );
}