"use client";

import { useEffect, useRef } from "react";
import { useTheme } from "@/hooks/use-theme";
import { useSidebarConfig } from "@/contexts/sidebar-context";
import { useThemeManager } from "@/hooks/use-theme-manager";
import { tweakcnThemes } from "@/config/theme-data";
import type { ThemePrefs } from "@/lib/appwrite/theme-prefs-actions";

export function PrefsInitializer({ prefs }: { prefs: ThemePrefs }) {
  const { setTheme } = useTheme();
  const { updateConfig } = useSidebarConfig();
  const { applyTheme, applyTweakcnTheme, applyRadius } = useThemeManager();
  const applied = useRef(false);

  useEffect(() => {
    if (applied.current) return;
    applied.current = true;

    // Dark/light mode
    if (prefs.theme) setTheme(prefs.theme);

    // Determine isDark for CSS variable application
    const isDark =
      prefs.theme === "dark" ||
      (prefs.theme !== "light" &&
        typeof window !== "undefined" &&
        window.matchMedia("(prefers-color-scheme: dark)").matches);

    // Radius
    if (prefs.radius) applyRadius(prefs.radius);

    // Color theme (shadcn presets)
    if (prefs.colorTheme) {
      applyTheme(prefs.colorTheme, isDark);
    }

    // Tweakcn theme
    if (prefs.tweakcnTheme) {
      const preset = tweakcnThemes.find((t) => t.value === prefs.tweakcnTheme)?.preset;
      if (preset) applyTweakcnTheme(preset, isDark);
    }

    // Sidebar config
    if (prefs.sidebarVariant || prefs.sidebarCollapsible || prefs.sidebarSide) {
      updateConfig({
        ...(prefs.sidebarVariant && { variant: prefs.sidebarVariant }),
        ...(prefs.sidebarCollapsible && { collapsible: prefs.sidebarCollapsible }),
        ...(prefs.sidebarSide && { side: prefs.sidebarSide }),
      });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return null;
}
