import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
import { trpc } from "@/lib/trpc";
import { buildAppearanceCssVariables } from "@/lib/appearance";
import { defaultPortalAppearance, type AppearanceThemeMode, type PortalAppearance } from "@shared/appearance";

type Theme = AppearanceThemeMode;
type ResolvedTheme = "light" | "dark";

interface ThemeContextType {
  theme: Theme;
  resolvedTheme: ResolvedTheme;
  appearance: PortalAppearance;
  toggleTheme?: () => void;
  switchable: boolean;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

interface ThemeProviderProps {
  children: React.ReactNode;
  defaultTheme?: Theme;
  switchable?: boolean;
}

export function ThemeProvider({
  children,
  defaultTheme = "light",
  switchable = false,
}: ThemeProviderProps) {
  const { data: appearance } = trpc.settings.getAppearance.useQuery(undefined, {
    staleTime: 1000 * 60 * 5,
    refetchOnWindowFocus: false,
  });

  const [theme, setTheme] = useState<Theme>(() => {
    if (switchable) {
      const stored = localStorage.getItem("theme");
      return (stored as Theme) || defaultTheme;
    }
    return defaultTheme;
  });
  const [systemTheme, setSystemTheme] = useState<ResolvedTheme>("light");

  useEffect(() => {
    if (typeof window === "undefined") {
      return;
    }

    const media = window.matchMedia("(prefers-color-scheme: dark)");
    const syncSystemTheme = () => setSystemTheme(media.matches ? "dark" : "light");
    syncSystemTheme();
    media.addEventListener("change", syncSystemTheme);

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

  useEffect(() => {
    if (!switchable && appearance?.themeMode) {
      setTheme(appearance.themeMode);
    }
  }, [appearance?.themeMode, switchable]);

  const resolvedTheme = theme === "system" ? systemTheme : theme;
  const resolvedAppearance = appearance || defaultPortalAppearance;
  const cssVariables = useMemo(
    () => buildAppearanceCssVariables(resolvedAppearance, resolvedTheme),
    [resolvedAppearance, resolvedTheme]
  );

  useEffect(() => {
    const root = document.documentElement;
    if (resolvedTheme === "dark") {
      root.classList.add("dark");
    } else {
      root.classList.remove("dark");
    }

    Object.entries(cssVariables).forEach(([key, value]) => {
      root.style.setProperty(key, value);
    });

    root.dataset.cardStyle = resolvedAppearance.cardStyle;
    root.dataset.tableStyle = resolvedAppearance.tableStyle;
    root.dataset.displayDensity = resolvedAppearance.displayDensity;
    root.dataset.sidebarStyle = resolvedAppearance.sidebarStyle;
    root.dataset.buttonStyle = resolvedAppearance.buttonStyle;
    root.dataset.inputStyle = resolvedAppearance.inputStyle;

    if (switchable) {
      localStorage.setItem("theme", theme);
    }
  }, [cssVariables, resolvedAppearance, resolvedTheme, theme, switchable]);

  useEffect(() => {
    if (typeof document === "undefined") {
      return;
    }

    const titleBase = resolvedAppearance.portalTitle?.trim() || defaultPortalAppearance.portalTitle;
    if (!document.title || document.title === defaultPortalAppearance.portalTitle) {
      document.title = titleBase;
    }

    const faviconHref = resolvedAppearance.faviconUrl?.trim();
    let link = document.querySelector("link[rel='icon']") as HTMLLinkElement | null;
    if (!link) {
      link = document.createElement("link");
      link.rel = "icon";
      document.head.appendChild(link);
    }

    if (faviconHref) {
      link.href = faviconHref;
    }
  }, [resolvedAppearance.faviconUrl, resolvedAppearance.portalTitle]);

  const toggleTheme = switchable
    ? () => {
        setTheme(prev => {
          if (prev === "light") return "dark";
          if (prev === "dark") return "system";
          return "light";
        });
      }
    : undefined;

  return (
    <ThemeContext.Provider value={{ theme, resolvedTheme, appearance: resolvedAppearance, toggleTheme, switchable }}>
      {children}
    </ThemeContext.Provider>
  );
}

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