/**
 * Markdown 渲染组件
 *
 * 提供：
 * - Markdown 渲染（使用 react-markdown + remark-gfm）
 * - 代码高亮（使用 react-syntax-highlighter）
 * - 优化的样式和交互
 * - 复制代码功能
 */
import React, { useState } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { Button, message } from 'antd'
import { CopyOutlined, CheckOutlined } from '@ant-design/icons'
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism'

interface MarkdownRendererProps {
  content: string
  className?: string
  style?: React.CSSProperties
}

// 代码块语言映射
const languageMap: Record<string, string> = {
  javascript: 'javascript',
  js: 'javascript',
  jsx: 'jsx',
  typescript: 'typescript',
  ts: 'typescript',
  tsx: 'tsx',
  python: 'python',
  py: 'python',
  java: 'java',
  cpp: 'cpp',
  c: 'c',
  css: 'css',
  html: 'html',
  xml: 'xml',
  json: 'json',
  yaml: 'yaml',
  yml: 'yaml',
  bash: 'bash',
  shell: 'bash',
  sql: 'sql',
  markdown: 'markdown',
  md: 'markdown'
}

export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
  content,
  className = '',
  style = {}
}) => {
  const [copiedCode, setCopiedCode] = useState<string | null>(null)

  // 复制代码到剪贴板
  const copyToClipboard = (code: string, language?: string) => {
    navigator.clipboard.writeText(code).then(() => {
      setCopiedCode(language || code.substring(0, 50))
      message.success('代码已复制到剪贴板')
      setTimeout(() => setCopiedCode(null), 2000)
    })
  }

  return (
    <div className={`markdown-renderer ${className}`} style={style}>
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        components={{
          // 代码块渲染
          code({ node, inline, className, children, ...props }: any) {
            const match = /language-(\w+)/.exec(className || '')
            const language = match ? match[1] : 'text'
            const codeString = String(children).replace(/\n$/, '')

            if (inline) {
              return (
                <code className={className} {...props}>
                  {children}
                </code>
              )
            }

            return (
              <div style={{ position: 'relative' }}>
                <div style={{
                  background: '#f5f5f5',
                  padding: '8px 12px',
                  borderRadius: '4px 4px 0 0',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  borderBottom: '1px solid #e8e8e8'
                }}>
                  <span style={{
                    fontSize: '12px',
                    color: '#666',
                    fontFamily: 'monospace'
                  }}>
                    {language}
                  </span>
                  <Button
                    size="small"
                    type="text"
                    icon={copiedCode === codeString ? <CheckOutlined /> : <CopyOutlined />}
                    onClick={() => copyToClipboard(codeString, language)}
                    style={{ fontSize: '12px' }}
                  >
                    {copiedCode === codeString ? '已复制' : '复制'}
                  </Button>
                </div>
                <SyntaxHighlighter
                  language={languageMap[language] || language}
                  style={vscDarkPlus}
                  customStyle={{
                    margin: 0,
                    borderRadius: '0 0 4px 4px',
                    fontSize: '13px',
                    lineHeight: '1.5'
                  }}
                  PreTag="div"
                >
                  {codeString}
                </SyntaxHighlighter>
              </div>
            )
          },

          // 标题渲染
          h1({ children }: any) {
            return <h1 style={{
              fontSize: '2em',
              fontWeight: 'bold',
              marginTop: '1.5em',
              marginBottom: '0.5em',
              paddingBottom: '0.3em',
              borderBottom: '2px solid #1890ff'
            }}>{children}</h1>
          },
          h2({ children }: any) {
            return <h2 style={{
              fontSize: '1.5em',
              fontWeight: '600',
              marginTop: '1.5em',
              marginBottom: '0.5em',
              paddingBottom: '0.3em',
              borderBottom: '1px solid #d9d9d9'
            }}>{children}</h2>
          },
          h3({ children }: any) {
            return <h3 style={{
              fontSize: '1.25em',
              fontWeight: '600',
              marginTop: '1em',
              marginBottom: '0.5em'
            }}>{children}</h3>
          },
          h4({ children }: any) {
            return <h4 style={{
              fontSize: '1em',
              fontWeight: '600',
              marginTop: '0.8em',
              marginBottom: '0.5em'
            }}>{children}</h4>
          },

          // 段落渲染
          p({ children }: any) {
            return <p style={{
              lineHeight: '1.7',
              marginBottom: '1em'
            }}>{children}</p>
          },

          // 列表渲染
          ul({ children }: any) {
            return <ul style={{
              paddingLeft: '20px',
              marginBottom: '1em',
              listStyle: 'disc'
            }}>{children}</ul>
          },
          ol({ children }: any) {
            return <ol style={{
              paddingLeft: '20px',
              marginBottom: '1em',
              listStyle: 'decimal'
            }}>{children}</ol>
          },
          li({ children }: any) {
            return <li style={{
              marginBottom: '0.5em',
              lineHeight: '1.7'
            }}>{children}</li>
          },

          // 引用块渲染
          blockquote({ children }: any) {
            return (
              <blockquote style={{
                borderLeft: '4px solid #1890ff',
                paddingLeft: '16px',
                marginLeft: 0,
                marginRight: 0,
                fontStyle: 'italic',
                color: '#666',
                background: '#f9f9f9',
                padding: '8px 16px',
                marginBottom: '1em'
              }}>
                {children}
              </blockquote>
            )
          },

          // 表格渲染
          table({ children }: any) {
            return (
              <div style={{ overflowX: 'auto', marginBottom: '1em' }}>
                <table style={{
                  borderCollapse: 'collapse',
                  width: '100%',
                  border: '1px solid #d9d9d9'
                }}>
                  {children}
                </table>
              </div>
            )
          },
          thead({ children }: any) {
            return (
              <thead style={{ background: '#fafafa' }}>
                {children}
              </thead>
            )
          },
          tbody({ children }: any) {
            return <tbody>{children}</tbody>
          },
          tr({ children }: any) {
            return (
              <tr>
                {children}
              </tr>
            )
          },
          th({ children }: any) {
            return (
              <th style={{
                border: '1px solid #d9d9d9',
                padding: '12px',
                textAlign: 'left',
                fontWeight: 600,
                background: '#fafafa'
              }}>
                {children}
              </th>
            )
          },
          td({ children }: any) {
            return (
              <td style={{
                border: '1           solid #d9d9d9',
                padding: '12px'
              }}>
                {children}
              </td>
            )
          },

          // 水平分割线
          hr({ ...props }: any) {
            return <hr style={{
              border: 'none',
              borderTop: '1px solid #d9d9d9',
              margin: '2em 0'
            }} {...props} />
          },

          // 强调文本
          strong({ children }: any) {
            return <strong style={{ color: '#262626', fontWeight: 600 }}>{children}</strong>
          },

          // 链接
          a({ href, children }: any) {
            return (
              <a
                href={href}
                target="_blank"
                rel="noopener noreferrer"
                style={{ color: '#1890ff', textDecoration: 'none' }}
              >
                {children}
              </a>
            )
          },

          // 图片
          img({ src, alt }: any) {
            return (
              <img
                src={src}
                alt={alt}
                style={{
                  maxWidth: '100%',
                  height: 'auto',
                  borderRadius: '4px',
                  margin: '8px 0'
                }}
              />
            )
          }
        }}
      >
        {content}
      </ReactMarkdown>

      <style>{`
        .markdown-renderer {
          line-height: 1.7;
          color: #262626;
        }

        .markdown-renderer pre {
          background: #f5f5f5;
          padding: 0;
          border-radius: 4px;
          overflow-x: auto;
          margin: '1em 0';
        }

        .markdown-renderer code {
          fontFamily: 'Consolas, Monaco, "Courier New", monospace;
          fontSize: 13px;
        }

        .markdown-renderer :global(pre > code) {
          display: block;
        }

        .markdown-renderer :global(p > code) {
          background: '#f5f5f5';
          padding: '2px 6px';
          borderRadius: '3px';
          fontSize: '0.9em;
          color: '#e01e5e';
        }
      `}</style>
    </div>
  )
}
