import { useState, useMemo } from 'react';
import { Input } from 'antd';
import {
  ALL_TEMPLATES,
  COLOR_THEMES,
  applyTheme,
  getColorTheme,
} from './articleTemplates';

interface ArticleStyleLibraryProps {
  isDark: boolean;
  onInsertTemplate: (html: string) => void;
  selectedTheme: string;
  onThemeChange: (themeId: string) => void;
}

const sectionLabel = (_text: string, isDark: boolean) => ({
  fontSize: 12,
  fontWeight: 600,
  color: isDark ? '#64748b' : '#86868b',
  padding: '12px 14px 6px',
  textTransform: 'uppercase' as const,
  letterSpacing: 0.5,
});

/**
 * 左栏样式组件库
 * 提供标题样式、内容模板、区块组件和配色方案。
 */
export default function ArticleStyleLibrary({
  isDark,
  onInsertTemplate,
  selectedTheme,
  onThemeChange,
}: ArticleStyleLibraryProps) {
  const [searchKeyword, setSearchKeyword] = useState('');

  const theme = useMemo(() => getColorTheme(selectedTheme), [selectedTheme]);

  const filteredTemplates = useMemo(() => {
    if (!searchKeyword.trim()) return ALL_TEMPLATES;
    const kw = searchKeyword.toLowerCase();
    return ALL_TEMPLATES.filter(
      (t) =>
        t.name.toLowerCase().includes(kw) ||
        t.category.toLowerCase().includes(kw),
    );
  }, [searchKeyword]);

  const handleInsert = (template: typeof ALL_TEMPLATES[number]) => {
    const html = applyTheme(template.html, theme);
    onInsertTemplate(html);
  };

  const headingFiltered = filteredTemplates.filter(
    (t) => t.category === 'heading',
  );
  const contentFiltered = filteredTemplates.filter(
    (t) => t.category === 'content',
  );
  const blockFiltered = filteredTemplates.filter(
    (t) => t.category === 'block',
  );

  const cardBg = isDark ? '#1e293b' : '#fff';
  const cardBorder = isDark ? '#334155' : '#e5e5ea';
  const panelBg = isDark ? '#0f172a' : '#fafafa';

  const renderSection = (
    label: string,
    templates: typeof ALL_TEMPLATES,
  ) => {
    if (templates.length === 0) return null;
    return (
      <>
        <div style={sectionLabel(label, isDark)}>{label}</div>
        {templates.map((t) => (
          <div
            key={t.id}
            onClick={() => handleInsert(t)}
            style={{
              margin: '0 12px 8px',
              padding: 12,
              background: cardBg,
              borderRadius: 8,
              border: `1px solid ${cardBorder}`,
              cursor: 'pointer',
              transition: 'border-color 0.15s, box-shadow 0.15s',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.borderColor = theme.primary;
              e.currentTarget.style.boxShadow = `0 0 0 1px ${theme.primary}`;
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.borderColor = cardBorder;
              e.currentTarget.style.boxShadow = 'none';
            }}
          >
            <div
              style={{
                fontSize: 13,
                fontWeight: 500,
                color: isDark ? '#e2e8f0' : '#1d1d1f',
                marginBottom: 2,
              }}
            >
              {t.name}
            </div>
            <div
              style={{
                fontSize: 12,
                color: isDark ? '#94a3b8' : '#6e6e73',
                background: isDark ? '#1e293b' : '#f5f5f7',
                padding: '5px 8px',
                borderRadius: 4,
                lineHeight: 1.4,
                marginTop: 4,
              }}
            >
              {t.preview}
            </div>
          </div>
        ))}
      </>
    );
  };

  return (
    <div
      style={{
        width: 240,
        flexShrink: 0,
        background: panelBg,
        borderRight: `1px solid ${isDark ? '#1e293b' : '#e5e5ea'}`,
        overflow: 'auto',
        height: '100%',
      }}
    >
      {/* 搜索框 */}
      <div style={{ padding: '10px 10px 6px' }}>
        <Input
          size="small"
          placeholder="搜索样式模板..."
          value={searchKeyword}
          onChange={(e) => setSearchKeyword(e.target.value)}
          allowClear
          style={{ borderRadius: 8 }}
        />
      </div>

      {/* 配色方案 */}
      <div style={sectionLabel('配色方案', isDark)}>配色方案</div>
      <div
        style={{
          display: 'flex',
          gap: 8,
          padding: '0 14px',
          marginBottom: 4,
        }}
      >
        {COLOR_THEMES.map((c) => (
          <div
            key={c.id}
            title={c.name}
            onClick={() => onThemeChange(c.id)}
            style={{
              width: 24,
              height: 24,
              borderRadius: '50%',
              background: c.primary,
              cursor: 'pointer',
              border:
                selectedTheme === c.id
                  ? `2px solid ${isDark ? '#fff' : '#1d1d1f'}`
                  : '2px solid transparent',
              transition: 'border-color 0.15s, transform 0.1s',
              transform: selectedTheme === c.id ? 'scale(1.15)' : 'scale(1)',
            }}
          />
        ))}
      </div>

      {/* 模板列表 */}
      {renderSection('标题样式', headingFiltered)}
      {renderSection('内容模板', contentFiltered)}
      {renderSection('区块组件', blockFiltered)}

      {/* 无结果 */}
      {filteredTemplates.length === 0 && (
        <div
          style={{
            padding: '24px 14px',
            textAlign: 'center',
            color: isDark ? '#64748b' : '#86868b',
            fontSize: 13,
          }}
        >
          未找到匹配的模板
        </div>
      )}
    </div>
  );
}
