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

function Breadcrumbs({ filePath }) {
  const breadcrumbs = generateBreadcrumbs(filePath);
  if (breadcrumbs.length === 0) return null;

  return (
    <nav className="breadcrumbs" aria-label="当前位置">
      {breadcrumbs.map((crumb, index) => (
        <span key={crumb.path} className="breadcrumb-item">
          {index > 0 && <span className="breadcrumb-separator">/</span>}
          <span className="breadcrumb-text">{crumb.name}</span>
        </span>
      ))}
    </nav>
  );
}

function CodeBlock({ inline, className, children, ...props }) {
  const [copied, setCopied] = useState(false);

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

  const codeText = React.Children.toArray(children).join('').replace(/\n$/, '');
  const match = /language-(\w+)/.exec(className || '');
  const language = match ? match[1] : 'text';
  const buttonClass = 'code-copy-button' + (copied ? ' copied' : '');
  const buttonLabel = copied ? '已复制' : '复制代码';

  const handleCopy = async () => {
    if (typeof navigator === 'undefined' || !navigator.clipboard) {
      return;
    }

    try {
      await navigator.clipboard.writeText(codeText);
      setCopied(true);
      setTimeout(() => setCopied(false), 2200);
    } catch (error) {
      console.error('Failed to copy code block', error);
    }
  };

  return (
    <div className="code-block-wrapper">
      <div className="code-block-header">
        <span className="code-language">{language}</span>
        <button type="button" className={buttonClass} onClick={handleCopy} aria-live="polite">
          {buttonLabel}
        </button>
      </div>
      <pre className={className} {...props}>
        <code>{children}</code>
      </pre>
    </div>
  );
}

function CustomLink({ href, children, ...props }) {
  if (href && href.startsWith('[[') && href.endsWith(']]')) {
    const linkText = href.slice(2, -2);
    return (
      <span className="internal-link" title={`内部链接: ${linkText}`}>
        {children || linkText}
      </span>
    );
  }

  const isExternal = href && /^(https?:)?\/\//.test(href);
  const linkClass = isExternal ? 'external-link' : 'internal-link';

  return (
    <a
      href={href}
      target={isExternal ? '_blank' : '_self'}
      rel={isExternal ? 'noopener noreferrer' : undefined}
      className={linkClass}
      {...props}
    >
      {children}
      {isExternal && <span className="external-link-icon" aria-hidden>🔗</span>}
    </a>
  );
}

function CustomTable({ children, ...props }) {
  return (
    <div className="table-wrapper">
      <table {...props}>{children}</table>
    </div>
  );
}

function createHeadingRenderer(tag) {
  return function HeadingRenderer({ children, ...props }) {
    const text = React.Children.toArray(children)
      .map((child) => {
        if (typeof child === 'string') return child;
        if (React.isValidElement(child) && typeof child.props.children === 'string') {
          return child.props.children;
        }
        return '';
      })
      .join(' ')
      .trim();

    const id = text
      .toLowerCase()
      .replace(/[^a-z0-9\u00c0-\u024f\u4e00-\u9fa5\s-]/g, '')
      .replace(/\s+/g, '-');

    const HeadingTag = tag;

    return (
      <HeadingTag id={id} {...props}>
        <a href={`#${id}`} aria-hidden className="heading-anchor">
          #
        </a>
        {children}
      </HeadingTag>
    );
  };
}

const headingComponents = {
  h1: createHeadingRenderer('h1'),
  h2: createHeadingRenderer('h2'),
  h3: createHeadingRenderer('h3'),
  h4: createHeadingRenderer('h4'),
};

export default function MarkdownRenderer() {
  const { currentFile, currentContent, isLoading, sidebarOpen } = useApp();

  const components = useMemo(
    () => ({
      code: CodeBlock,
      a: CustomLink,
      table: CustomTable,
      ...headingComponents,
      blockquote: ({ children, ...props }) => (
        <blockquote className="custom-blockquote" {...props}>
          {children}
        </blockquote>
      ),
      img: ({ alt, ...props }) => (
        <figure className="markdown-image">
          <img alt={alt} {...props} />
          {alt && <figcaption>{alt}</figcaption>}
        </figure>
      ),
    }),
    [],
  );

  const contentAreaClass = 'content-area' + (sidebarOpen ? ' with-sidebar' : '');

  if (!currentFile) {
    return (
      <div className={contentAreaClass}>
        <div className="welcome-message">
          <div className="welcome-content">
            <h1>🌙 欢迎回来</h1>
            <p>从左侧目录选择任意 Markdown 笔记即可开始阅读。</p>
            <div className="welcome-features">
              <div className="feature-item">
                <span className="feature-icon">📝</span>
                <span>原汁原味的 Markdown 样式</span>
              </div>
              <div className="feature-item">
                <span className="feature-icon">💡</span>
                <span>深色界面，夜间更护眼</span>
              </div>
              <div className="feature-item">
                <span className="feature-icon">⚡</span>
                <span>代码高亮与复制一键搞定</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const fileTitle = getFileTitle(currentFile.split('/').pop(), currentContent);

  return (
    <div className={contentAreaClass}>
      <div className="content-header">
        <Breadcrumbs filePath={currentFile} />
        <h1 className="content-title">{fileTitle}</h1>
      </div>

      <div className="content-body">
        <div className="markdown-pane">
          {isLoading ? (
            <div className="loading-content">
              <div className="loading-spinner" aria-hidden />
              <span>加载中...</span>
            </div>
          ) : (
            <div className="markdown-content">
              <ReactMarkdown
                remarkPlugins={[remarkGfm, remarkMath, remarkBreaks]}
                rehypePlugins={[rehypeRaw, rehypeKatex, rehypeHighlight]}
                components={components}
              >
                {currentContent}
              </ReactMarkdown>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
