import React, { createContext, useContext, useState, useEffect, ReactNode } from "react";

// 디자인 토큰 인터페이스
export interface DesignTokens {
  // Colors
  background: string;
  foreground: string;
  card: string;
  cardForeground: string;
  popover: string;
  popoverForeground: string;
  primary: string;
  primaryForeground: string;
  secondary: string;
  secondaryForeground: string;
  muted: string;
  mutedForeground: string;
  accent: string;
  accentForeground: string;
  destructive: string;
  destructiveForeground: string;
  border: string;
  input: string;
  inputBackground: string;
  switchBackground: string;
  ring: string;
  
  // Chart Colors
  chart1: string;
  chart2: string;
  chart3: string;
  chart4: string;
  chart5: string;
  
  // Spacing
  radius: string;
  
  // Shadows
  shadowSm: string;
  shadow: string;
  shadowLg: string;
  shadowXl: string;
  
  // Typography
  fontSize: string;
  fontWeightMedium: string;
  fontWeightNormal: string;
  
  // Sidebar
  sidebar: string;
  sidebarForeground: string;
  sidebarPrimary: string;
  sidebarPrimaryForeground: string;
  sidebarAccent: string;
  sidebarAccentForeground: string;
  sidebarBorder: string;
  sidebarRing: string;
}

// 기본 토큰 값 (globals.css에서 가져옴)
const defaultTokens: DesignTokens = {
  background: "#FAFAFA",
  foreground: "#1A1A1A",
  card: "#FFFFFF",
  cardForeground: "#1A1A1A",
  popover: "#FFFFFF",
  popoverForeground: "#1A1A1A",
  primary: "#3B82F6",
  primaryForeground: "#FFFFFF",
  secondary: "#F1F5F9",
  secondaryForeground: "#1A1A1A",
  muted: "#F8FAFC",
  mutedForeground: "#6B7280",
  accent: "#F0F9FF",
  accentForeground: "#1A1A1A",
  destructive: "#EF4444",
  destructiveForeground: "#FFFFFF",
  border: "#E2E8F0",
  input: "#FFFFFF",
  inputBackground: "#F8FAFC",
  switchBackground: "#F1F5F9",
  ring: "rgba(59, 130, 246, 0.3)",
  
  chart1: "#3B82F6",
  chart2: "#10B981",
  chart3: "#F59E0B",
  chart4: "#EF4444",
  chart5: "#8B5CF6",
  
  radius: "0.75rem",
  
  shadowSm: "0 1px 2px rgba(0, 0, 0, 0.05)",
  shadow: "0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06)",
  shadowLg: "0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06)",
  shadowXl: "0 10px 15px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05)",
  
  fontSize: "16px",
  fontWeightMedium: "500",
  fontWeightNormal: "400",
  
  sidebar: "#FFFFFF",
  sidebarForeground: "#1A1A1A",
  sidebarPrimary: "#3B82F6",
  sidebarPrimaryForeground: "#FFFFFF",
  sidebarAccent: "#F0F9FF",
  sidebarAccentForeground: "#1A1A1A",
  sidebarBorder: "#E2E8F0",
  sidebarRing: "rgba(59, 130, 246, 0.3)",
};

interface DesignTokenContextType {
  tokens: DesignTokens;
  updateToken: (key: keyof DesignTokens, value: string) => void;
  updateTokens: (newTokens: Partial<DesignTokens>) => void;
  resetTokens: () => void;
  applyTheme: (theme: "light" | "dark") => void;
  currentTheme: "light" | "dark";
}

const DesignTokenContext = createContext<DesignTokenContextType | undefined>(undefined);

export function DesignTokenProvider({ children }: { children: ReactNode }) {
  const [tokens, setTokens] = useState<DesignTokens>(defaultTokens);
  const [currentTheme, setCurrentTheme] = useState<"light" | "dark">("light");

  // localStorage에서 토큰 로드
  useEffect(() => {
    const savedTokens = localStorage.getItem("designTokens");
    const savedTheme = localStorage.getItem("designTheme") as "light" | "dark" | null;
    
    if (savedTokens) {
      try {
        const parsed = JSON.parse(savedTokens);
        setTokens(parsed);
        applyTokensToDOM(parsed);
      } catch (error) {
        console.error("Failed to parse saved tokens:", error);
      }
    }
    
    if (savedTheme) {
      setCurrentTheme(savedTheme);
      applyThemeClass(savedTheme);
    }
  }, []);

  // DOM에 CSS 변수 적용
  const applyTokensToDOM = (newTokens: DesignTokens) => {
    const root = document.documentElement;
    
    // CSS 변수 매핑
    const cssVarMap: Record<keyof DesignTokens, string> = {
      background: "--background",
      foreground: "--foreground",
      card: "--card",
      cardForeground: "--card-foreground",
      popover: "--popover",
      popoverForeground: "--popover-foreground",
      primary: "--primary",
      primaryForeground: "--primary-foreground",
      secondary: "--secondary",
      secondaryForeground: "--secondary-foreground",
      muted: "--muted",
      mutedForeground: "--muted-foreground",
      accent: "--accent",
      accentForeground: "--accent-foreground",
      destructive: "--destructive",
      destructiveForeground: "--destructive-foreground",
      border: "--border",
      input: "--input",
      inputBackground: "--input-background",
      switchBackground: "--switch-background",
      ring: "--ring",
      chart1: "--chart-1",
      chart2: "--chart-2",
      chart3: "--chart-3",
      chart4: "--chart-4",
      chart5: "--chart-5",
      radius: "--radius",
      shadowSm: "--clean-shadow-sm",
      shadow: "--clean-shadow",
      shadowLg: "--clean-shadow-lg",
      shadowXl: "--clean-shadow-xl",
      fontSize: "--font-size",
      fontWeightMedium: "--font-weight-medium",
      fontWeightNormal: "--font-weight-normal",
      sidebar: "--sidebar",
      sidebarForeground: "--sidebar-foreground",
      sidebarPrimary: "--sidebar-primary",
      sidebarPrimaryForeground: "--sidebar-primary-foreground",
      sidebarAccent: "--sidebar-accent",
      sidebarAccentForeground: "--sidebar-accent-foreground",
      sidebarBorder: "--sidebar-border",
      sidebarRing: "--sidebar-ring",
    };

    Object.entries(newTokens).forEach(([key, value]) => {
      const cssVar = cssVarMap[key as keyof DesignTokens];
      if (cssVar) {
        root.style.setProperty(cssVar, value);
      }
    });
  };

  // 테마 클래스 적용
  const applyThemeClass = (theme: "light" | "dark") => {
    const root = document.documentElement;
    root.classList.remove("light", "dark");
    if (theme !== "light") {
      root.classList.add(theme);
    }
  };

  // 단일 토큰 업데이트
  const updateToken = (key: keyof DesignTokens, value: string) => {
    const newTokens = { ...tokens, [key]: value };
    setTokens(newTokens);
    applyTokensToDOM(newTokens);
    localStorage.setItem("designTokens", JSON.stringify(newTokens));
  };

  // 여러 토큰 업데이트
  const updateTokens = (newTokens: Partial<DesignTokens>) => {
    const updatedTokens = { ...tokens, ...newTokens };
    setTokens(updatedTokens);
    applyTokensToDOM(updatedTokens);
    localStorage.setItem("designTokens", JSON.stringify(updatedTokens));
  };

  // 토큰 리셋
  const resetTokens = () => {
    setTokens(defaultTokens);
    applyTokensToDOM(defaultTokens);
    localStorage.removeItem("designTokens");
  };

  // 테마 적용
  const applyTheme = (theme: "light" | "dark") => {
    setCurrentTheme(theme);
    applyThemeClass(theme);
    localStorage.setItem("designTheme", theme);
    
    // 테마에 맞는 기본 토큰 적용
    if (theme === "dark") {
      const darkTokens: Partial<DesignTokens> = {
        background: "#0F172A",
        foreground: "#F8FAFC",
        card: "#1E293B",
        cardForeground: "#F8FAFC",
        primary: "#60A5FA",
        primaryForeground: "#1E293B",
        border: "#334155",
        shadowSm: "0 1px 2px rgba(0, 0, 0, 0.3)",
        shadow: "0 1px 3px rgba(0, 0, 0, 0.4), 0 1px 2px rgba(0, 0, 0, 0.3)",
      };
      updateTokens(darkTokens);
    } else {
      resetTokens();
    }
  };

  return (
    <DesignTokenContext.Provider
      value={{
        tokens,
        updateToken,
        updateTokens,
        resetTokens,
        applyTheme,
        currentTheme,
      }}
    >
      {children}
    </DesignTokenContext.Provider>
  );
}

export function useDesignTokens() {
  const context = useContext(DesignTokenContext);
  if (context === undefined) {
    throw new Error("useDesignTokens must be used within a DesignTokenProvider");
  }
  return context;
}
