/**
 * ThemeSystem
 * Provides consistent design system and theming across all CMS components
 */

import React, {
  createContext,
  useContext,
  useState,
  useCallback,
  useMemo,
} from "react";
import {
  ThemeConfig,
  StyleConfig,
  ComponentType,
} from "../types/components.js";

// ========================================
// Types & Interfaces
// ========================================

export interface ThemeSystemProps {
  children: React.ReactNode;
  defaultTheme?: ThemeConfig;
  themes?: Record<string, ThemeConfig>;
  onThemeChange?: (theme: ThemeConfig) => void;
}

export interface ThemeContextValue {
  currentTheme: ThemeConfig;
  availableThemes: Record<string, ThemeConfig>;
  setTheme: (themeId: string) => void;
  updateTheme: (updates: Partial<ThemeConfig>) => void;
  getComponentStyles: (
    componentType: ComponentType,
    variant?: string
  ) => StyleConfig;
  applyThemeToStyles: (styles: StyleConfig) => StyleConfig;
}

export interface ThemeControlsProps {
  position?: "top-left" | "top-right" | "bottom-left" | "bottom-right";
  showPreview?: boolean;
  editable?: boolean;
}

export interface ColorPaletteProps {
  theme: ThemeConfig;
  onColorChange: (colorKey: keyof ThemeConfig, color: string) => void;
  editable: boolean;
}

export interface TypographyControlsProps {
  theme: ThemeConfig;
  onTypographyChange: (updates: Partial<ThemeConfig>) => void;
  editable: boolean;
}

// ========================================
// Default Themes
// ========================================

const DEFAULT_THEME: ThemeConfig = {
  primary: "#3b82f6",
  secondary: "#6b7280",
  accent: "#10b981",
  background: "#ffffff",
  surface: "#f9fafb",
  text: "#1f2937",
  textSecondary: "#6b7280",
  border: "#e5e7eb",
  error: "#ef4444",
  warning: "#f59e0b",
  success: "#10b981",
  info: "#3b82f6",
  shadow: "0 1px 3px rgba(0, 0, 0, 0.1)",
};

const AVAILABLE_THEMES: Record<string, ThemeConfig> = {
  default: DEFAULT_THEME,
  dark: {
    primary: "#60a5fa",
    secondary: "#9ca3af",
    accent: "#34d399",
    background: "#111827",
    surface: "#1f2937",
    text: "#f9fafb",
    textSecondary: "#d1d5db",
    border: "#374151",
    error: "#f87171",
    warning: "#fbbf24",
    success: "#34d399",
    info: "#60a5fa",
    shadow: "0 1px 3px rgba(0, 0, 0, 0.3)",
  },
  minimal: {
    primary: "#000000",
    secondary: "#666666",
    accent: "#000000",
    background: "#ffffff",
    surface: "#fafafa",
    text: "#000000",
    textSecondary: "#666666",
    border: "#e0e0e0",
    error: "#d32f2f",
    warning: "#ff9800",
    success: "#388e3c",
    info: "#1976d2",
    shadow: "0 1px 2px rgba(0, 0, 0, 0.05)",
  },
};

// ========================================
// Theme Context
// ========================================

const ThemeContext = createContext<ThemeContextValue | null>(null);

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

// ========================================
// Color Palette Component
// ========================================

export const ColorPalette: React.FC<ColorPaletteProps> = ({
  theme,
  onColorChange,
  editable,
}) => {
  const colorKeys = Object.keys(theme) as Array<keyof ThemeConfig>;

  if (!editable) {
    return (
      <div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
        {colorKeys.map((key) => (
          <div
            key={key}
            style={{
              width: "2rem",
              height: "2rem",
              backgroundColor: theme[key],
              borderRadius: "0.25rem",
              border: "1px solid #e5e7eb",
            }}
            title={`${key}: ${theme[key]}`}
          />
        ))}
      </div>
    );
  }

  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))",
        gap: "1rem",
      }}
    >
      {colorKeys.map((key) => (
        <div
          key={key}
          style={{ display: "flex", flexDirection: "column", gap: "0.25rem" }}
        >
          <label
            style={{
              fontSize: "0.875rem",
              fontWeight: "500",
              textTransform: "capitalize",
            }}
          >
            {key.replace(/([A-Z])/g, " $1").toLowerCase()}
          </label>
          <div style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}>
            <input
              type="color"
              value={theme[key]}
              onChange={(e) => onColorChange(key, e.target.value)}
              style={{
                width: "2rem",
                height: "2rem",
                border: "none",
                borderRadius: "0.25rem",
                cursor: "pointer",
              }}
            />
            <input
              type="text"
              value={theme[key]}
              onChange={(e) => onColorChange(key, e.target.value)}
              style={{
                flex: 1,
                padding: "0.25rem 0.5rem",
                border: "1px solid #d1d5db",
                borderRadius: "0.25rem",
                fontSize: "0.875rem",
                fontFamily: "monospace",
              }}
            />
          </div>
        </div>
      ))}
    </div>
  );
};

// ========================================
// Theme Controls Component
// ========================================

export const ThemeControls: React.FC<ThemeControlsProps> = ({
  position = "top-right",
  showPreview = true,
  editable = true,
}) => {
  const { currentTheme, availableThemes, setTheme, updateTheme } = useTheme();
  const [showControls, setShowControls] = useState(false);
  const [activeTab, setActiveTab] = useState<
    "themes" | "colors" | "typography"
  >("themes");

  const positionStyles = useMemo(() => {
    const base: React.CSSProperties = {
      position: "fixed",
      zIndex: 1000,
    };

    switch (position) {
      case "top-left":
        return { ...base, top: "1rem", left: "1rem" };
      case "top-right":
        return { ...base, top: "1rem", right: "1rem" };
      case "bottom-left":
        return { ...base, bottom: "1rem", left: "1rem" };
      case "bottom-right":
        return { ...base, bottom: "1rem", right: "1rem" };
      default:
        return { ...base, top: "1rem", right: "1rem" };
    }
  }, [position]);

  const handleColorChange = useCallback(
    (colorKey: keyof ThemeConfig, color: string) => {
      updateTheme({ [colorKey]: color });
    },
    [updateTheme]
  );

  if (!editable) return null;

  return (
    <div style={positionStyles}>
      <button
        onClick={() => setShowControls(!showControls)}
        style={{
          background: currentTheme.primary,
          color: currentTheme.background,
          border: "none",
          borderRadius: "0.5rem",
          padding: "0.5rem 1rem",
          fontSize: "0.875rem",
          fontWeight: "500",
          cursor: "pointer",
          boxShadow: "0 4px 6px rgba(0, 0, 0, 0.1)",
        }}
      >
        🎨 Theme
      </button>

      {showControls && (
        <div
          style={{
            position: "absolute",
            top: "3rem",
            right: "0",
            width: "400px",
            maxHeight: "500px",
            backgroundColor: currentTheme.surface,
            border: `1px solid ${currentTheme.border}`,
            borderRadius: "0.5rem",
            boxShadow: "0 10px 25px rgba(0, 0, 0, 0.15)",
            overflow: "hidden",
          }}
        >
          {/* Header */}
          <div
            style={{
              padding: "1rem",
              borderBottom: `1px solid ${currentTheme.border}`,
              backgroundColor: currentTheme.background,
            }}
          >
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <h3
                style={{
                  margin: 0,
                  fontSize: "1rem",
                  fontWeight: "600",
                  color: currentTheme.text,
                }}
              >
                Theme Settings
              </h3>
              <button
                onClick={() => setShowControls(false)}
                style={{
                  background: "none",
                  border: "none",
                  fontSize: "1.25rem",
                  cursor: "pointer",
                  color: currentTheme.textSecondary,
                }}
              >
                ×
              </button>
            </div>

            {/* Tabs */}
            <div style={{ display: "flex", gap: "0.5rem", marginTop: "1rem" }}>
              {(["themes", "colors", "typography"] as const).map((tab) => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  style={{
                    padding: "0.5rem 1rem",
                    border: "none",
                    borderRadius: "0.25rem",
                    fontSize: "0.875rem",
                    cursor: "pointer",
                    backgroundColor:
                      activeTab === tab ? currentTheme.primary : "transparent",
                    color:
                      activeTab === tab
                        ? currentTheme.background
                        : currentTheme.textSecondary,
                    textTransform: "capitalize",
                  }}
                >
                  {tab}
                </button>
              ))}
            </div>
          </div>

          {/* Content */}
          <div
            style={{ padding: "1rem", maxHeight: "350px", overflowY: "auto" }}
          >
            {activeTab === "themes" && (
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: "0.75rem",
                }}
              >
                {Object.entries(availableThemes).map(([themeId, theme]) => (
                  <button
                    key={themeId}
                    onClick={() => setTheme(themeId)}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: "0.75rem",
                      padding: "0.75rem",
                      border: `2px solid ${
                        currentTheme === theme
                          ? currentTheme.primary
                          : currentTheme.border
                      }`,
                      borderRadius: "0.375rem",
                      backgroundColor: currentTheme.background,
                      cursor: "pointer",
                      textAlign: "left",
                    }}
                  >
                    <div style={{ display: "flex", gap: "0.25rem" }}>
                      <div
                        style={{
                          width: "1rem",
                          height: "1rem",
                          backgroundColor: theme.primary,
                          borderRadius: "50%",
                        }}
                      />
                      <div
                        style={{
                          width: "1rem",
                          height: "1rem",
                          backgroundColor: theme.secondary,
                          borderRadius: "50%",
                        }}
                      />
                      <div
                        style={{
                          width: "1rem",
                          height: "1rem",
                          backgroundColor: theme.accent,
                          borderRadius: "50%",
                        }}
                      />
                    </div>
                    <span
                      style={{
                        fontSize: "0.875rem",
                        fontWeight: "500",
                        color: currentTheme.text,
                        textTransform: "capitalize",
                      }}
                    >
                      {themeId}
                    </span>
                  </button>
                ))}
              </div>
            )}

            {activeTab === "colors" && (
              <ColorPalette
                theme={currentTheme}
                onColorChange={handleColorChange}
                editable={editable}
              />
            )}

            {activeTab === "typography" && (
              <div
                style={{
                  color: currentTheme.textSecondary,
                  textAlign: "center",
                  padding: "2rem",
                }}
              >
                Typography controls coming soon...
              </div>
            )}
          </div>

          {/* Preview */}
          {showPreview && (
            <div
              style={{
                padding: "1rem",
                borderTop: `1px solid ${currentTheme.border}`,
                backgroundColor: currentTheme.background,
              }}
            >
              <div
                style={{
                  fontSize: "0.875rem",
                  fontWeight: "500",
                  marginBottom: "0.5rem",
                  color: currentTheme.text,
                }}
              >
                Preview
              </div>
              <div
                style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}
              >
                <button
                  style={{
                    backgroundColor: currentTheme.primary,
                    color: currentTheme.background,
                    border: "none",
                    borderRadius: "0.25rem",
                    padding: "0.25rem 0.5rem",
                    fontSize: "0.75rem",
                  }}
                >
                  Primary
                </button>
                <button
                  style={{
                    backgroundColor: currentTheme.accent,
                    color: currentTheme.background,
                    border: "none",
                    borderRadius: "0.25rem",
                    padding: "0.25rem 0.5rem",
                    fontSize: "0.75rem",
                  }}
                >
                  Accent
                </button>
                <div
                  style={{
                    backgroundColor: currentTheme.surface,
                    border: `1px solid ${currentTheme.border}`,
                    borderRadius: "0.25rem",
                    padding: "0.25rem 0.5rem",
                    fontSize: "0.75rem",
                    color: currentTheme.text,
                  }}
                >
                  Surface
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// ========================================
// Main ThemeSystem Component
// ========================================

export const ThemeSystem: React.FC<ThemeSystemProps> = ({
  children,
  defaultTheme = DEFAULT_THEME,
  themes = AVAILABLE_THEMES,
  onThemeChange,
}) => {
  const [currentTheme, setCurrentTheme] = useState<ThemeConfig>(defaultTheme);

  const setTheme = useCallback(
    (themeId: string) => {
      const theme = themes[themeId];
      if (theme) {
        setCurrentTheme(theme);
        if (onThemeChange) {
          onThemeChange(theme);
        }
      }
    },
    [themes, onThemeChange]
  );

  const updateTheme = useCallback(
    (updates: Partial<ThemeConfig>) => {
      const newTheme = { ...currentTheme, ...updates };
      setCurrentTheme(newTheme);
      if (onThemeChange) {
        onThemeChange(newTheme);
      }
    },
    [currentTheme, onThemeChange]
  );

  const getComponentStyles = useCallback(
    (_componentType: ComponentType, _variant?: string): StyleConfig => {
      // Simplified component styles for now
      return {
        color: currentTheme.text,
        backgroundColor: currentTheme.background,
      };
    },
    [currentTheme]
  );

  const applyThemeToStyles = useCallback(
    (styles: StyleConfig): StyleConfig => {
      return {
        ...styles,
        // Note: CSS custom properties would be applied at runtime
        // This is a simplified version for TypeScript compatibility
      };
    },
    [currentTheme]
  );

  const contextValue: ThemeContextValue = useMemo(
    () => ({
      currentTheme,
      availableThemes: themes,
      setTheme,
      updateTheme,
      getComponentStyles,
      applyThemeToStyles,
    }),
    [
      currentTheme,
      themes,
      setTheme,
      updateTheme,
      getComponentStyles,
      applyThemeToStyles,
    ]
  );

  return (
    <ThemeContext.Provider value={contextValue}>
      <div
        style={{
          backgroundColor: currentTheme.background,
          color: currentTheme.text,
          minHeight: "100vh",
          transition: "background-color 0.2s ease, color 0.2s ease",
        }}
      >
        {children}
        <ThemeControls />
      </div>
    </ThemeContext.Provider>
  );
};
