import React, { useState, useRef, useEffect } from 'react';
import styles from './index.module.css';

const FORMATS = [
  { key: 'pdf', label: 'PDF', desc: '适合打印和离线阅读' },
  { key: 'markdown', label: 'Markdown', desc: '可编辑的 Markdown 文件' },
  { key: 'html', label: 'HTML', desc: '保留样式的网页文件' },
  { key: 'txt', label: 'TXT', desc: '纯文本文件' },
];

function getDocTitle() {
  const h1 = document.querySelector('article header h1');
  return h1 ? h1.textContent.trim() : document.title;
}

function getArticleContent() {
  return document.querySelector('article .markdown') || document.querySelector('article');
}

function downloadFile(filename, content, mimeType) {
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

async function exportPDF(element, title) {
  const html2pdf = (await import('html2pdf.js')).default;
  html2pdf()
    .set({
      margin: [15, 15, 15, 15],
      filename: `${title}.pdf`,
      image: { type: 'jpeg', quality: 0.98 },
      html2canvas: { scale: 2, useCORS: true },
      jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
    })
    .from(element)
    .save();
}

async function exportMarkdown(element, title) {
  const TurndownService = (await import('turndown')).default;
  const turndown = new TurndownService({
    headingStyle: 'atx',
    codeBlockStyle: 'fenced',
  });
  const md = `# ${title}\n\n${turndown.turndown(element.innerHTML)}`;
  downloadFile(`${title}.md`, md, 'text/markdown;charset=utf-8');
}

function exportHTML(element, title) {
  const html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${title}</title>
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      max-width: 800px;
      margin: 2rem auto;
      padding: 0 1rem;
      color: #333;
      line-height: 1.6;
    }
    h1, h2, h3 { color: #1b2440; }
    pre { background: #f6f8fa; padding: 1rem; border-radius: 6px; overflow-x: auto; }
    code { background: #f6f8fa; padding: 0.2em 0.4em; border-radius: 3px; font-size: 85%; }
    img { max-width: 100%; height: auto; }
    a { color: #466aff; }
    table { border-collapse: collapse; width: 100%; }
    th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
    th { background: #f6f8fa; }
  </style>
</head>
<body>
  <h1>${title}</h1>
  ${element.innerHTML}
</body>
</html>`;
  downloadFile(`${title}.html`, html, 'text/html;charset=utf-8');
}

function exportTXT(element, title) {
  const text = `${title}\n${'='.repeat(title.length)}\n\n${element.innerText}`;
  downloadFile(`${title}.txt`, text, 'text/plain;charset=utf-8');
}

const handlers = { pdf: exportPDF, markdown: exportMarkdown, html: exportHTML, txt: exportTXT };

export default function ExportButton() {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    function handleClickOutside(e) {
      if (ref.current && !ref.current.contains(e.target)) {
        setOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  async function handleExport(format) {
    setOpen(false);
    const content = getArticleContent();
    if (!content) return;
    setLoading(true);
    try {
      await handlers[format](content, getDocTitle());
    } catch (err) {
      console.error('Export failed:', err);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className={styles.wrapper}>
      <div className={styles.exportBtn} ref={ref}>
        <button
          className={styles.button}
          onClick={() => setOpen((v) => !v)}
          disabled={loading}
        >
          <svg className={styles.icon} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
            <polyline points="7,10 12,15 17,10" />
            <line x1="12" y1="15" x2="12" y2="3" />
          </svg>
          {loading ? '导出中…' : '导出'}
          {!loading && <span className={styles.arrow}>&#9662;</span>}
        </button>
        {open && (
          <ul className={styles.dropdown}>
            {FORMATS.map((f) => (
              <li key={f.key} className={styles.item} onClick={() => handleExport(f.key)}>
                <span className={styles.formatLabel}>{f.label}</span>
                <span className={styles.formatDesc}>{f.desc}</span>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
