import * as React from 'react'

type Props = {
  doc: string
  width: number
  onResizeStart: (e: React.MouseEvent) => void
}

function wordCount(s: string): number {
  return s.replace(/[\u4e00-\u9fff]/g, ' $& ').split(/[\s]+/).filter(Boolean).length
}

function codeBlockCount(s: string): number {
  return Math.floor(((s.match(/```/g) || []).length) / 2)
}

function imageCount(s: string): number {
  return (s.match(/!\[.*?\]\(.*?\)/g) || []).length
}

function linkCount(s: string): number {
  return (s.match(/\[.*?\]\(.*?\)/g) || []).length
}

function tableCount(s: string): number {
  return (s.match(/^\|.+\|.+\|/gm) || []).length
}

function blockquoteCount(s: string): number {
  return (s.match(/^>\s/gm) || []).length
}

function listItemCount(s: string): number {
  return (s.match(/^(?:[-*+]|\d+\.)\s/gm) || []).length
}

function mermaidCount(s: string): number {
  return (s.match(/```mermaid\n?/gi) || []).length
}

function headingCount(s: string): number {
  return (s.match(/^#{1,6}\s/gm) || []).length
}

function boldCount(s: string): number {
  return (s.match(/\*\*[^*]+\*\*/g) || []).length
}

function italicCount(s: string): number {
  return (s.match(/(?<!\*)\*[^*\n]+\*(?!\*)/g) || []).length
}

function inlineCodeCount(s: string): number {
  return (s.match(/`[^`\n]+`/g) || []).length
}

function taskCount(s: string): { done: number; total: number } {
  const tasks = s.match(/^\s*[-*+]\s+\[([ x])\]/gm) || []
  const done = tasks.filter((t) => t.includes('[x]')).length
  return { done, total: tasks.length }
}

function docSize(s: string): string {
  const sizeKB = new Blob([s]).size / 1024
  return sizeKB < 1 ? '<1 KB' : `${Math.round(sizeKB)} KB`
}

export function StatsPanel({ doc, width, onResizeStart }: Props): React.ReactElement {
  return (
    <>
      <div className="stats-resize" onMouseDown={onResizeStart} title="拖动调整统计栏宽度" />
      <aside className="stats-panel" style={{ width, minWidth: width }}>
        <div className="stats-panel-header">
          <span className="stats-panel-header-icon">📊</span>
          文档统计
        </div>
        <div className="stats-panel-body">
          <div className="stats-panel-section">
            <div className="stats-panel-section-title">字数</div>
            <div className="stats-panel-grid">
              <div className="stats-panel-item">
                <span className="stats-panel-value">{doc.length.toLocaleString()}</span>
                <span className="stats-panel-label">字符</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{doc.replace(/\s/g, '').length.toLocaleString()}</span>
                <span className="stats-panel-label">字（无空格）</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{wordCount(doc).toLocaleString()}</span>
                <span className="stats-panel-label">词</span>
              </div>
            </div>
          </div>
          <div className="stats-panel-section">
            <div className="stats-panel-section-title">结构</div>
            <div className="stats-panel-grid">
              <div className="stats-panel-item">
                <span className="stats-panel-value">{doc === '' ? 0 : doc.split('\n').length}</span>
                <span className="stats-panel-label">行</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{doc.split(/\n\s*\n/).filter((p) => p.trim().length > 0).length}</span>
                <span className="stats-panel-label">段落</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{Math.max(1, Math.round(wordCount(doc) / 300))}</span>
                <span className="stats-panel-label">分钟阅读</span>
              </div>
            </div>
          </div>
          <div className="stats-panel-section">
            <div className="stats-panel-section-title">元素</div>
            <div className="stats-panel-grid">
              <div className="stats-panel-item">
                <span className="stats-panel-value">{codeBlockCount(doc)}</span>
                <span className="stats-panel-label">代码块</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{imageCount(doc)}</span>
                <span className="stats-panel-label">图片</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{linkCount(doc)}</span>
                <span className="stats-panel-label">链接</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{tableCount(doc)}</span>
                <span className="stats-panel-label">表格</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{blockquoteCount(doc)}</span>
                <span className="stats-panel-label">引用</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{listItemCount(doc)}</span>
                <span className="stats-panel-label">列表项</span>
              </div>
            </div>
          </div>
          <div className="stats-panel-section">
            <div className="stats-panel-section-title">图表</div>
            <div className="stats-panel-grid">
              <div className="stats-panel-item">
                <span className="stats-panel-value">{mermaidCount(doc)}</span>
                <span className="stats-panel-label">Mermaid</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{docSize(doc)}</span>
                <span className="stats-panel-label">文档大小</span>
              </div>
            </div>
          </div>
          <div className="stats-panel-section">
            <div className="stats-panel-section-title">格式</div>
            <div className="stats-panel-grid">
              <div className="stats-panel-item">
                <span className="stats-panel-value">{headingCount(doc)}</span>
                <span className="stats-panel-label">标题</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{boldCount(doc)}</span>
                <span className="stats-panel-label">加粗</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{italicCount(doc)}</span>
                <span className="stats-panel-label">斜体</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{inlineCodeCount(doc)}</span>
                <span className="stats-panel-label">行内代码</span>
              </div>
              <div className="stats-panel-item">
                <span className="stats-panel-value">{taskCount(doc).done}/{taskCount(doc).total}</span>
                <span className="stats-panel-label">任务</span>
              </div>
            </div>
          </div>
        </div>
      </aside>
    </>
  )
}