"use client";

import { useEffect, useRef } from "react";

import { useSidebarConfig } from "@/contexts/sidebar-context";
import { useTheme } from "@/hooks/use-theme";
import { useThemeManager } from "@/hooks/use-theme-manager";
import { tweakcnThemes } from "@/config/theme-data";
import type { UserPrefs as ThemePrefs } from "@/lib/appwrite/user-prefs-actions";
import { getLocalThemePrefs } from "@/lib/local-theme-prefs";

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;

    // localStorage wins (most recent change on this device); Appwrite prefs are fallback
    const local = getLocalThemePrefs();
    const effectiveTheme = prefs.theme;
    const effectiveColorTheme = local.colorTheme ?? prefs.colorTheme;
    const effectiveTweakcnTheme = local.tweakcnTheme ?? prefs.tweakcnTheme;
    const effectiveRadius = local.radius ?? prefs.radius;
    const effectiveSidebarVariant = (local.sidebarVariant as ThemePrefs["sidebarVariant"]) ?? prefs.sidebarVariant;
    const effectiveSidebarCollapsible = (local.sidebarCollapsible as ThemePrefs["sidebarCollapsible"]) ?? prefs.sidebarCollapsible;
    const effectiveSidebarSide = (local.sidebarSide as ThemePrefs["sidebarSide"]) ?? prefs.sidebarSide;

    if (effectiveTheme) setTheme(effectiveTheme);

    const isDark =
      effectiveTheme === "dark" ||
      (effectiveTheme !== "light" &&
        typeof window !== "undefined" &&
        window.matchMedia("(prefers-color-scheme: dark)").matches);

    if (effectiveRadius) applyRadius(effectiveRadius);

    if (effectiveColorTheme) {
      applyTheme(effectiveColorTheme, isDark);
    }

    if (effectiveTweakcnTheme) {
      const preset = tweakcnThemes.find((t) => t.value === effectiveTweakcnTheme)?.preset;
      if (preset) applyTweakcnTheme(preset, isDark);
    }

    if (effectiveSidebarVariant || effectiveSidebarCollapsible || effectiveSidebarSide) {
      updateConfig({
        ...(effectiveSidebarVariant && { variant: effectiveSidebarVariant }),
        ...(effectiveSidebarCollapsible && { collapsible: effectiveSidebarCollapsible }),
        ...(effectiveSidebarSide && { side: effectiveSidebarSide }),
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return null;
}
