import { useState, useMemo } from 'react'
import type { PromptEnvelope } from '../types/protocol'
import { exportToOpenAIFormat } from '../utils/export'
import { Code, Copy, Download, Check } from 'lucide-react'

interface ProtocolPanelProps {
  envelope: PromptEnvelope
}

type Tab = 'openai' | 'raw'

export default function ProtocolPanel({ envelope }: ProtocolPanelProps) {
  const [activeTab, setActiveTab] = useState<Tab>('openai')
  const [copied, setCopied] = useState(false)

  const openaiFormat = useMemo(() => exportToOpenAIFormat(envelope), [envelope])
  const rawProtocolJson = useMemo(() => JSON.stringify(envelope, null, 2), [envelope])

  const displayedJson = activeTab === 'openai'
    ? JSON.stringify(openaiFormat, null, 2)
    : rawProtocolJson

  const downloadFilename = activeTab === 'openai'
    ? 'openai-export.json'
    : 'prompt-envelope.json'

  const handleCopy = async () => {
    await navigator.clipboard.writeText(displayedJson)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const handleDownload = () => {
    const blob = new Blob([displayedJson], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = downloadFilename
    a.click()
    URL.revokeObjectURL(url)
  }

  /** 统计 envelope 中的 segment 数量 */
  const segmentStats = useMemo(() => {
    const counts: Record<string, number> = {}
    for (const msg of envelope.messages) {
      for (const seg of msg.segments) {
        counts[seg.kind] = (counts[seg.kind] || 0) + 1
      }
    }
    return counts
  }, [envelope])

  const totalSegments = Object.values(segmentStats).reduce((a, b) => a + b, 0)

  return (
    <div className="w-96 border-l border-gray-200 bg-white flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center gap-2 px-4 py-3 border-b border-gray-100">
        <Code size={18} className="text-gray-500" />
        <span className="text-sm font-semibold text-gray-700 flex-1">
          Protocol View
        </span>
        <button
          onClick={handleCopy}
          className="flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-500 hover:bg-gray-100 transition-colors"
        >
          {copied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
          {copied ? '已复制' : '复制'}
        </button>
        <button
          onClick={handleDownload}
          className="flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-500 hover:bg-gray-100 transition-colors"
        >
          <Download size={14} />
          下载
        </button>
      </div>

      {/* Tabs */}
      <div className="flex text-xs border-b border-gray-100">
        <button
          onClick={() => setActiveTab('openai')}
          className={`flex-1 text-center py-2 transition-colors cursor-pointer ${
            activeTab === 'openai'
              ? 'font-semibold text-blue-600 border-b-2 border-blue-500 bg-blue-50/50'
              : 'text-gray-400 hover:text-gray-600 hover:bg-gray-50'
          }`}
        >
          OpenAI Format
        </button>
        <button
          onClick={() => setActiveTab('raw')}
          className={`flex-1 text-center py-2 transition-colors cursor-pointer ${
            activeTab === 'raw'
              ? 'font-semibold text-blue-600 border-b-2 border-blue-500 bg-blue-50/50'
              : 'text-gray-400 hover:text-gray-600 hover:bg-gray-50'
          }`}
        >
          Raw Protocol
        </button>
      </div>

      {/* JSON Content */}
      <div className="flex-1 overflow-y-auto">
        <pre className="p-4 text-xs font-mono text-gray-600 whitespace-pre-wrap break-all leading-relaxed">
          {displayedJson}
        </pre>
      </div>

      {/* Footer stats */}
      <div className="px-4 py-2 border-t border-gray-100 text-[10px] text-gray-400 flex items-center gap-3 flex-wrap">
        {activeTab === 'openai' ? (
          <>
            <span>model: {openaiFormat.model}</span>
            <span>{envelope.messages.length} 条协议消息</span>
            <span>{openaiFormat.messages.length} OpenAI messages</span>
            {openaiFormat.tools && <span>{openaiFormat.tools.length} tools</span>}
          </>
        ) : (
          <>
            <span>version: {envelope.version}</span>
            {envelope.model && <span>model: {envelope.model}</span>}
            <span>{envelope.messages.length} 条消息</span>
            <span>{totalSegments} 个 segment</span>
            <span>{Object.keys(segmentStats).length} 种类型</span>
          </>
        )}
      </div>
    </div>
  )
}
