import React, { useEffect, useRef, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import remarkBreaks from 'remark-breaks';
import rehypeKatex from 'rehype-katex';
import rehypeHighlight from 'rehype-highlight';
import rehypeRaw from 'rehype-raw';
import { useApp } from '../context/AppContext';
import './MarkdownRenderer.css';
import 'github-markdown-css/github-markdown-light.css';
import 'katex/dist/katex.min.css';
import 'highlight.js/styles/github.css';

function MarkdownRenderer() {
  const { currentContent, currentFile, currentMetadata, isLoading, error, directoryTree } = useApp();
  const contentRef = useRef(null);
  const [copySuccess, setCopySuccess] = useState(false);
  const [codeCopySuccess, setCodeCopySuccess] = useState({});

  // 语言到文件扩展名的映射
  const languageExtensions = {
    javascript: 'js',
    typescript: 'ts',
    python: 'py',
    java: 'java',
    cpp: 'cpp',
    c: 'c',
    csharp: 'cs',
    go: 'go',
    rust: 'rs',
    php: 'php',
    ruby: 'rb',
    swift: 'swift',
    kotlin: 'kt',
    scala: 'scala',
    html: 'html',
    css: 'css',
    sql: 'sql',
    bash: 'sh',
    shell: 'sh',
    json: 'json',
    xml: 'xml',
    yaml: 'yaml',
    markdown: 'md',
    dart: 'dart',
    r: 'r',
    matlab: 'm',
  };

  // 复制代码块
  const handleCodeCopy = async (code, index) => {
    try {
      await navigator.clipboard.writeText(code);
      setCodeCopySuccess({ ...codeCopySuccess, [index]: true });
      setTimeout(() => {
        setCodeCopySuccess({ ...codeCopySuccess, [index]: false });
      }, 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  // 下载代码块
  const handleCodeDownload = (code, language) => {
    const extension = languageExtensions[language?.toLowerCase()] || 'txt';
    const blob = new Blob([code], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `code.${extension}`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (!bytes) return '0 B';
    const kb = bytes / 1024;
    if (kb < 1024) return `${kb.toFixed(2)} KB`;
    const mb = kb / 1024;
    if (mb < 1024) return `${mb.toFixed(2)} MB`;
    const gb = mb / 1024;
    return `${gb.toFixed(2)} GB`;
  };

  // 获取文件名（不带.md后缀）
  const getFileName = () => {
    if (!currentFile) return '';
    const fileName = currentFile.split('/').pop();
    return fileName.replace(/\.md$/i, '');
  };

  // 构建当前笔记的完整 URL（显示用：保留中文原文）
  const getNoteUrlDisplay = () => {
    if (!currentFile) return '';
    return `${window.location.origin}/note/${currentFile}`;
  };

  // 构建当前笔记的完整 URL（复制用：每段 encodeURIComponent）
  const getNoteUrlEncoded = () => {
    if (!currentFile) return '';
    const encoded = currentFile.split('/').map(encodeURIComponent).join('/');
    return `${window.location.origin}/note/${encoded}`;
  };

  const [pathCopied, setPathCopied] = useState(false);

  const handleCopyPath = async () => {
    const url = getNoteUrlEncoded();
    if (!url) return;
    try {
      // 优先用 Clipboard API，降级到 execCommand
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(url);
      } else {
        const ta = document.createElement('textarea');
        ta.value = url;
        ta.style.cssText = 'position:fixed;opacity:0;top:0;left:0';
        document.body.appendChild(ta);
        ta.focus();
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
      }
      setPathCopied(true);
      setTimeout(() => setPathCopied(false), 2000);
    } catch {
      /* ignore */
    }
  };

  // 复制内容到剪贴板
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(currentContent);
      setCopySuccess(true);
      setTimeout(() => setCopySuccess(false), 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  // 下载Markdown文件
  const handleDownload = () => {
    const blob = new Blob([currentContent], { type: 'text/markdown' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${getFileName()}.md`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // 当内容变化时，滚动到顶部
  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.scrollTop = 0;
    }
    // 重置复制状态
    setCopySuccess(false);
    setCodeCopySuccess({});
  }, [currentFile]);

  return (
    <div className="markdown-renderer" ref={contentRef}>
      <div className="markdown-container">
        {isLoading && (
          <div className="loading-state">
            <div className="loading-spinner"></div>
            <p>加载中...</p>
          </div>
        )}
        
        {error && !isLoading && (
          <div className="error-state">
            <div className="error-icon">⚠️</div>
            <h2>加载失败</h2>
            <p>{error}</p>
          </div>
        )}
        
        {!isLoading && !error && !currentContent && (
          <div className="empty-state" style={{ padding: '50px', textAlign: 'center', color: '#888' }}>
            {directoryTree.length === 0 ? (
              <>
                <p>当前没有可展示的笔记</p>
                <p style={{ fontSize: '0.8em', marginTop: '10px', maxWidth: '420px', marginLeft: 'auto', marginRight: 'auto' }}>
                  目录树为空。若已部署后端，请检查笔记目录挂载与 /api/health 中的 markdown_root。
                </p>
              </>
            ) : (
              <>
                <p>请选择左侧文件查看内容</p>
                <p style={{ fontSize: '0.8em', marginTop: '10px' }}>Select a file to view content</p>
              </>
            )}
          </div>
        )}

        {!isLoading && !error && currentContent && (
          <>
            {/* 文件头部：文件名 + 操作按钮 */}
            <div className="file-header">
              <h1 className="file-title">{getFileName()}</h1>
              <div className="file-actions">
                <button 
                  className="action-button copy-button" 
                  onClick={handleCopy}
                  title="复制内容"
                >
                  {copySuccess ? '✓ 已复制' : '⧉ 复制'}
                </button>
                <button 
                  className="action-button download-button" 
                  onClick={handleDownload}
                  title="下载文件"
                >
                  ⇩ 下载
                </button>
              </div>
            </div>

            <article className="markdown-body">
            <ReactMarkdown
              remarkPlugins={[
                remarkGfm,        // GitHub Flavored Markdown
                remarkMath,       // 数学公式支持
                remarkBreaks,     // 自动换行
              ]}
              rehypePlugins={[
                rehypeRaw,        // 支持HTML标签
                rehypeKatex,      // 数学公式渲染
                rehypeHighlight,  // 代码高亮
              ]}
              components={{
                // 自定义图片渲染，支持点击放大
                img: ({ node, ...props }) => (
                  <img
                    {...props}
                    loading="lazy"
                    onClick={(e) => {
                      // 可以添加图片预览功能
                      e.target.classList.toggle('zoomed');
                    }}
                    style={{ cursor: 'pointer' }}
                  />
                ),
                // 自定义链接渲染，外部链接在新标签页打开
                a: ({ node, href, children, ...props }) => {
                  const isExternal = href?.startsWith('http');
                  return (
                    <a
                      href={href}
                      target={isExternal ? '_blank' : undefined}
                      rel={isExternal ? 'noopener noreferrer' : undefined}
                      {...props}
                    >
                      {children}
                    </a>
                  );
                },
                // 自定义代码块渲染 - DeepSeek 风格
                pre: ({ node, children, ...props }) => {
                  // 获取 code 元素
                  const codeElement = children?.props;
                  const className = codeElement?.className || '';
                  const code = String(codeElement?.children || '').trim();
                  
                  // 提取语言
                  const match = /language-(\w+)/.exec(className);
                  const language = match ? match[1] : 'text';
                  
                  // 生成唯一索引
                  const codeIndex = `${language}-${code.substring(0, 20)}`;
                  
                  return (
                    <div className="code-block-wrapper">
                      <div className="code-block-header">
                        <span className="code-language">{language}</span>
                        <div className="code-actions">
                          <button
                            className="code-action-btn"
                            onClick={() => handleCodeCopy(code, codeIndex)}
                            title="复制代码"
                          >
                            {codeCopySuccess[codeIndex] ? '✓ 已复制' : '⧉ 复制'}
                          </button>
                          <button
                            className="code-action-btn"
                            onClick={() => handleCodeDownload(code, language)}
                            title="下载代码"
                          >
                            ⇩ 下载
                          </button>
                        </div>
                      </div>
                      <pre {...props}>{children}</pre>
                    </div>
                  );
                },
                // 自定义行内代码
                code: ({ node, inline, className, children, ...props }) => {
                  if (inline) {
                    return <code className={className} {...props}>{children}</code>;
                  }
                  return (
                    <code className={className} {...props}>
                      {children}
                    </code>
                  );
                }
              }}
            >
              {currentContent}
            </ReactMarkdown>
            
            {/* 文章底部信息栏：元数据 + 路径 */}
            <div className="file-metadata">
              <div className="metadata-divider"></div>
              <div className="metadata-content">
                {currentMetadata && (
                  <>
                    <div className="metadata-item" title="字数统计">
                      <span className="metadata-icon">📝</span>
                      <span className="metadata-label">字数:</span>
                      <span className="metadata-value">{currentMetadata.wordCount}</span>
                    </div>
                    <div className="metadata-item" title="文件大小">
                      <span className="metadata-icon">💾</span>
                      <span className="metadata-label">大小:</span>
                      <span className="metadata-value">{formatFileSize(currentMetadata.fileSize)}</span>
                    </div>
                    {currentMetadata.createdTime && (
                      <div className="metadata-item" title="创建时间">
                        <span className="metadata-icon">📅</span>
                        <span className="metadata-label">创建于:</span>
                        <span className="metadata-value">{currentMetadata.createdTime}</span>
                      </div>
                    )}
                    {currentMetadata.modifiedTime && (
                      <div className="metadata-item" title="修改时间">
                        <span className="metadata-icon">🕒</span>
                        <span className="metadata-label">最后修改于:</span>
                        <span className="metadata-value">{currentMetadata.modifiedTime}</span>
                      </div>
                    )}
                    <div className="metadata-divider-h"></div>
                  </>
                )}
                {/* 路径行 */}
                <button
                  type="button"
                  className={`note-path-bar${pathCopied ? ' note-path-bar--copied' : ''}`}
                  onClick={handleCopyPath}
                  title="点击复制链接"
                >
                  <span className="note-path-icon" aria-hidden>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
                      <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
                    </svg>
                  </span>
                  <span className="note-path-text">{getNoteUrlDisplay()}</span>
                  <span className="note-path-copy-hint">{pathCopied ? '✓ 已复制' : '复制'}</span>
                </button>
              </div>
            </div>
          </article>
          </>
        )}
      </div>
    </div>
  );
}

export default MarkdownRenderer;