import React, { useState, useEffect, useRef } from 'react';
import useAppLayoutStore from '../../../../Store/AppLayoutSlice';
import './ThemeToggle.css';

const themes = [
  {
    id: 'paper',
    name: '仿纸暖黄',
    description: '经典护眼，像 Kindle',
    icon: '📖',
    colors: {
      bg: '#F5ECD7',
      text: '#3E3A35',
      accent: '#8B9A6B'
    }
  },
  {
    id: 'modern',
    name: '现代清爽',
    description: '干净明快，适合网文',
    icon: '✨',
    colors: {
      bg: '#F8F8F8',
      text: '#2C2C2C',
      accent: '#4A9FB0'
    }
  },
  {
    id: 'dark',
    name: '夜间暗色',
    description: '黑底灰字，夜间必备',
    icon: '🌙',
    colors: {
      bg: '#1E1E1E',
      text: '#BDBBB6',
      accent: '#D4A76A'
    }
  },
  {
    id: 'green',
    name: '豆沙绿',
    description: '自然疗愈，绿色经典',
    icon: '🍃',
    colors: {
      bg: '#DCE5D9',
      text: '#2B3330',
      accent: '#7D9B7A'
    }
  }
];

const ThemeToggle = () => {
  const [isOpen, setIsOpen] = useState(false);
  const panelRef = useRef(null);
  
  // ✅ 从 Zustand store 获取主题状态和方法
  const { colorTheme, setColorTheme } = useAppLayoutStore();

  // ✅ 当 store 中的主题变化时，同步到 DOM
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', colorTheme);
    document.documentElement.setAttribute('data-color-theme', colorTheme);
  }, [colorTheme]);

  // 点击外部关闭面板
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (panelRef.current && !panelRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  const handleThemeSelect = (themeId) => {
    setColorTheme(themeId); // ✅ 使用 store 的方法
    setIsOpen(false);
  };

  const currentThemeData = themes.find(t => t.id === colorTheme) || themes[2];

  return (
    <div className="theme-toggle-wrapper" ref={panelRef}>
      <button
        className="action-btn theme-toggle"
        onClick={() => setIsOpen(!isOpen)}
        title="切换主题"
      >
        {currentThemeData.icon}
      </button>

      {/* 主题选择面板 */}
      {isOpen && (
        <div className="theme-selector-panel">
          <div className="theme-selector-header">
            <span className="theme-selector-title">选择主题</span>
          </div>
          <div className="theme-list">
            {themes.map(theme => (
              <button
                key={theme.id}
                className={`theme-item ${colorTheme === theme.id ? 'active' : ''}`}
                onClick={() => handleThemeSelect(theme.id)}
              >
                <div className="theme-item-icon">{theme.icon}</div>
                <div className="theme-item-info">
                  <div className="theme-item-name">{theme.name}</div>
                  <div className="theme-item-desc">{theme.description}</div>
                </div>
                <div className="theme-color-preview">
                  <div 
                    className="theme-color-bg" 
                    style={{ backgroundColor: theme.colors.bg }}
                  />
                  <div 
                    className="theme-color-accent" 
                    style={{ backgroundColor: theme.colors.accent }}
                  />
                </div>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default ThemeToggle;
