import { useState } from 'react'
import { API_BASE } from '../services/api.js'

// 友好显示 args（只展示几个关键字段，控制长度）
function formatArgs(args) {
  if (!args || typeof args !== 'object') return ''
  const out = []
  for (const k of Object.keys(args)) {
    let v = args[k]
    if (typeof v === 'string' && v.length > 80) v = v.slice(0, 80) + '…'
    if (typeof v === 'string') v = JSON.stringify(v)
    else v = JSON.stringify(v)
    out.push(`${k}: ${v}`)
  }
  return out.join(', ')
}

const TOOL_LABEL = {
  write_file: '写文件',
  read_file: '读文件',
  list_files: '列文件',
  create_html: '生成 HTML',
  create_word: '生成 Word',
  create_pdf: '生成 PDF',
  create_excel: '生成 Excel',
  create_pptx: '生成 PPT',
  web_search: '联网搜索',
  browser_automation: '浏览器操作',
  browser_screenshot: '网页截图',
}

const PREVIEWABLE_EXT = /\.(html?|pdf|md|markdown|txt|json|csv|svg|xml|ya?ml)$/i

// 优先用 onPreview 回调（右侧面板预览），没传回调时回退为新标签打开
function openPreview(onPreview, url, filename) {
  if (typeof onPreview === 'function') {
    onPreview(url, filename)
  } else {
    window.open(url, '_blank', 'noopener,noreferrer')
  }
}

export function ToolCallLine({ name, args }) {
  return (
    <div className="flex justify-start">
      <div className="max-w-[85%] text-[12px] text-blue-700 bg-blue-50 border border-blue-100 rounded-md px-3 py-1.5 break-words">
        <span className="font-medium">🔧 {TOOL_LABEL[name] || name}</span>
        <span className="text-blue-500/80 ml-1">({formatArgs(args)})</span>
      </div>
    </div>
  )
}

export function ToolResultLine({ name, result, sessionId, onPreview }) {
  const text = String(result || '')
  const preview = text.length > 200 ? text.slice(0, 200) + '…' : text
  const outputFiles = []
  if (sessionId && ['write_file', 'append_file', 'create_html', 'create_pdf', 'create_word', 'create_excel', 'create_pptx'].includes(name)) {
    const re = /([\w./_-]+\.(?:html?|pdf|docx|xlsx|pptx|md|txt|json|csv))\b/gi
    const seen = new Set()
    let m
    while ((m = re.exec(text)) !== null) {
      const f = m[1].replace(/^\/+/, '')
      if (!seen.has(f)) { seen.add(f); outputFiles.push(f) }
    }
  }
  return (
    <div className="flex justify-start">
      <div className="max-w-[85%] text-[12px] text-emerald-700 bg-emerald-50 border border-emerald-100 rounded-md px-3 py-1.5 whitespace-pre-wrap break-words">
        <span className="font-medium">✅ {TOOL_LABEL[name] || name}</span>
        <span className="text-emerald-600/80 ml-1">→ {preview}</span>
        {outputFiles.length > 0 && (
          <div className="mt-1.5 flex flex-wrap gap-1.5">
            {outputFiles.map((f) => {
              const baseUrl = `${API_BASE}/skill-run/outputs/${encodeURIComponent(sessionId)}/${encodeURIComponent(f)}`
              const canPreview = PREVIEWABLE_EXT.test(f)
              return (
                <span key={f} className="inline-flex items-center gap-1 bg-white border border-emerald-200 rounded text-[11px] overflow-hidden">
                  <span className="px-1.5 py-0.5 text-emerald-900" title={f}>{f}</span>
                  {canPreview && (
                    <button
                      type="button"
                      onClick={() => openPreview(onPreview, baseUrl, f)}
                      className="px-1.5 py-0.5 text-blue-600 hover:bg-blue-50 border-l border-emerald-100"
                    >预览</button>
                  )}
                  <a href={`${baseUrl}?dl=1`} className="px-1.5 py-0.5 text-emerald-600 hover:bg-emerald-100 border-l border-emerald-100">下载</a>
                </span>
              )
            })}
          </div>
        )}
      </div>
    </div>
  )
}

export function LimitReachedBox({ message, onContinue, disabled }) {
  return (
    <div className="flex justify-center">
      <div className="max-w-[90%] bg-blue-50 border border-blue-200 rounded-lg px-4 py-3 flex items-center gap-3">
        <div className="text-[12px] text-blue-800 flex-1">
          ⚠️ {message || '工具调用已达上限'}
        </div>
        <button
          onClick={onContinue}
          disabled={disabled}
          className="px-3 py-1.5 text-[12px] rounded-md text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition"
        >
          继续执行
        </button>
      </div>
    </div>
  )
}

export function FilesDownloadBox({ sessionId, files, onPreview }) {
  // 默认收起，点击展开。≤2 个文件时直接展开（避免无谓多一次点击）。
  const [expanded, setExpanded] = useState((files?.length || 0) <= 2)
  if (!sessionId || !files?.length) return null
  return (
    <div className="flex justify-start">
      <div className="max-w-[90%] bg-amber-50 border border-amber-200 rounded-lg px-3.5 py-2.5">
        <button
          type="button"
          onClick={() => setExpanded(v => !v)}
          className="text-[12px] font-medium text-amber-800 mb-1.5 inline-flex items-center gap-1 hover:text-amber-900"
        >
          📎 已生成 {files.length} 个文件
          <span className="text-amber-600 transition-transform" style={{ display: 'inline-block', transform: expanded ? 'rotate(180deg)' : 'rotate(0)' }}>▾</span>
        </button>
        {expanded && (
          <div className="flex flex-wrap gap-2">
            {files.map((name) => {
              const baseUrl = `${API_BASE}/skill-run/outputs/${encodeURIComponent(sessionId)}/${encodeURIComponent(name)}`
              const canPreview = PREVIEWABLE_EXT.test(name)
              return (
                <div key={name} className="flex items-center gap-1 bg-white border border-amber-200 rounded-md text-[12px] overflow-hidden">
                  <span className="px-2 py-1 text-amber-900 truncate max-w-[180px]" title={name}>{name}</span>
                  {canPreview && (
                    <button
                      type="button"
                      onClick={() => openPreview(onPreview, baseUrl, name)}
                      className="px-2 py-1 text-blue-600 hover:bg-blue-50 border-l border-amber-100"
                    >预览</button>
                  )}
                  <a
                    href={`${baseUrl}?dl=1`}
                    className="px-2 py-1 text-emerald-600 hover:bg-emerald-50 border-l border-amber-100"
                  >下载</a>
                </div>
              )
            })}
          </div>
        )}
      </div>
    </div>
  )
}
