import { fetchTheme, updateTheme as updateThemeApi, type ApiThemeSettings } from "@/lib/api/settings";

const STORAGE_KEY = "nexus-theme";

// ── Accent Colors ──

export type AccentColor = "amber" | "blue" | "emerald" | "violet" | "rose" | "cyan";

export const ACCENT_PRESETS: Record<AccentColor, { label: string; primary: string; ring: string; accent: string; preview: string }> = {
  amber: {
    label: "Amber",
    primary: "oklch(0.7 0.2 60)",
    ring: "oklch(0.7 0.2 60)",
    accent: "oklch(0.7 0.2 60 / 0.15)",
    preview: "#f59e0b",
  },
  blue: {
    label: "Blue",
    primary: "oklch(0.6 0.2 250)",
    ring: "oklch(0.6 0.2 250)",
    accent: "oklch(0.6 0.2 250 / 0.15)",
    preview: "#3b82f6",
  },
  emerald: {
    label: "Emerald",
    primary: "oklch(0.65 0.2 155)",
    ring: "oklch(0.65 0.2 155)",
    accent: "oklch(0.65 0.2 155 / 0.15)",
    preview: "#10b981",
  },
  violet: {
    label: "Violet",
    primary: "oklch(0.55 0.25 290)",
    ring: "oklch(0.55 0.25 290)",
    accent: "oklch(0.55 0.25 290 / 0.15)",
    preview: "#8b5cf6",
  },
  rose: {
    label: "Rose",
    primary: "oklch(0.6 0.2 15)",
    ring: "oklch(0.6 0.2 15)",
    accent: "oklch(0.6 0.2 15 / 0.15)",
    preview: "#f43f5e",
  },
  cyan: {
    label: "Cyan",
    primary: "oklch(0.7 0.15 200)",
    ring: "oklch(0.7 0.15 200)",
    accent: "oklch(0.7 0.15 200 / 0.15)",
    preview: "#06b6d4",
  },
};

// ── Mode ──

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

// ── Background Tone ──

export type BackgroundTone = "default" | "midnight" | "charcoal" | "slate" | "warm" | "cool";

export const DARK_TONES: { key: BackgroundTone; label: string; desc: string; preview: string }[] = [
  { key: "default", label: "Default", desc: "뉴트럴 다크", preview: "#1e1e1e" },
  { key: "midnight", label: "Midnight", desc: "딥 네이비", preview: "#0d1526" },
  { key: "charcoal", label: "Charcoal", desc: "웜 다크", preview: "#231f1b" },
  { key: "slate", label: "Slate", desc: "쿨 그레이", preview: "#1a2030" },
];

export const LIGHT_TONES: { key: BackgroundTone; label: string; desc: string; preview: string }[] = [
  { key: "default", label: "Default", desc: "뉴트럴 라이트", preview: "#f5f5f5" },
  { key: "warm", label: "Warm", desc: "아이보리 톤", preview: "#f5f0e8" },
  { key: "cool", label: "Cool", desc: "쿨 블루 톤", preview: "#eef1f6" },
];

// ── Settings ──

export type ThemeSettings = {
  accentColor: AccentColor;
  mode: ThemeMode;
  tone: BackgroundTone;
  showBlobs: boolean;
  chatBgImage: string;      // URL or empty string for none
  chatBgOpacity: number;    // 0 to 1
  chatBgScale: number;      // 1 = 100%, 2 = 200% etc.
  chatBgPositionX: number;  // 0-100 (percentage)
  chatBgPositionY: number;  // 0-100 (percentage)
};

const defaults: ThemeSettings = {
  accentColor: "amber",
  mode: "dark",
  tone: "default",
  showBlobs: true,
  chatBgImage: "/rubber-track.png",
  chatBgOpacity: 0.3,
  chatBgScale: 1.1,
  chatBgPositionX: 50,
  chatBgPositionY: 50,
};

/** Convert backend snake_case → frontend camelCase */
function fromApi(s: ApiThemeSettings): ThemeSettings {
  return {
    accentColor: s.accent_color as AccentColor,
    mode: s.mode as ThemeMode,
    tone: s.tone as BackgroundTone,
    showBlobs: s.show_blobs,
    chatBgImage: s.chat_bg_image,
    chatBgOpacity: s.chat_bg_opacity,
    chatBgScale: s.chat_bg_scale,
    chatBgPositionX: s.chat_bg_position_x,
    chatBgPositionY: s.chat_bg_position_y,
  };
}

/** Convert frontend camelCase → backend snake_case */
function toApi(t: ThemeSettings): ApiThemeSettings {
  return {
    accent_color: t.accentColor,
    mode: t.mode,
    tone: t.tone,
    show_blobs: t.showBlobs,
    chat_bg_image: t.chatBgImage,
    chat_bg_opacity: t.chatBgOpacity,
    chat_bg_scale: t.chatBgScale,
    chat_bg_position_x: t.chatBgPositionX,
    chat_bg_position_y: t.chatBgPositionY,
  };
}

/** Load theme from localStorage cache (sync, for initial render) */
export function loadTheme(): ThemeSettings {
  if (typeof window === "undefined") return defaults;
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    return raw ? { ...defaults, ...JSON.parse(raw) } : defaults;
  } catch {
    return defaults;
  }
}

/** Fetch theme from backend and update cache */
export async function loadThemeFromServer(): Promise<ThemeSettings> {
  try {
    const data = await fetchTheme();
    const theme = fromApi(data);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(theme));
    return theme;
  } catch {
    return loadTheme();
  }
}

/** Save theme to backend and update cache */
export async function saveTheme(settings: ThemeSettings): Promise<void> {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
  try {
    await updateThemeApi(toApi(settings));
  } catch {
    // localStorage already updated, server sync failed silently
  }
}

export function applyTheme(settings: ThemeSettings): void {
  const root = document.documentElement;

  // 1. Accent color
  const preset = ACCENT_PRESETS[settings.accentColor];
  if (preset) {
    // 라이트 모드에서는 primary를 약간 어둡게
    if (settings.mode === "light") {
      // oklch 값에서 lightness를 0.15 낮춤
      const darkPrimary = preset.primary.replace(/oklch\(([0-9.]+)/, (_, l) => `oklch(${Math.max(0.3, parseFloat(l) - 0.15)}`);
      const darkAccent = darkPrimary.replace(")", " / 0.12)");
      root.style.setProperty("--primary", darkPrimary);
      root.style.setProperty("--ring", darkPrimary);
      root.style.setProperty("--accent", darkAccent);
      root.style.setProperty("--sidebar-primary", darkPrimary);
      root.style.setProperty("--sidebar-ring", darkPrimary);
      root.style.setProperty("--sidebar-accent", darkAccent);
      root.style.setProperty("--sidebar-accent-foreground", darkPrimary);
    } else {
      root.style.setProperty("--primary", preset.primary);
      root.style.setProperty("--ring", preset.ring);
      root.style.setProperty("--accent", preset.accent);
      root.style.setProperty("--sidebar-primary", preset.primary);
      root.style.setProperty("--sidebar-ring", preset.ring);
      root.style.setProperty("--sidebar-accent", preset.accent);
      root.style.setProperty("--sidebar-accent-foreground", preset.primary);
    }
  }

  // 2. Mode class
  root.classList.remove("light", "dark");
  root.classList.add(settings.mode);

  // 3. Tone class
  root.classList.remove("tone-midnight", "tone-charcoal", "tone-slate", "tone-warm", "tone-cool");
  if (settings.tone !== "default") {
    root.classList.add(`tone-${settings.tone}`);
  }
}
