import { useEffect, useState } from 'react'
import { previewSession } from '../ipc'
import type { PreviewMessage } from '../types'
import { Modal } from './Modal'

interface Props {
  projectPath: string
  sessionId: string
  title: string
  onResume: () => void
  onClose: () => void
}

const ROLE_LABEL: Record<string, string> = {
  user: '用户',
  assistant: 'Claude',
  tool: '工具调用'
}

export function PreviewDialog({ projectPath, sessionId, title, onResume, onClose }: Props) {
  const [messages, setMessages] = useState<PreviewMessage[] | null>(null)
  const [error, setError] = useState('')

  useEffect(() => {
    previewSession(projectPath, sessionId)
      .then(setMessages)
      .catch((e) => setError(String(e)))
  }, [projectPath, sessionId])

  return (
    <Modal
      title={`预览：${title}`}
      width={680}
      onClose={onClose}
      footer={
        <>
          <button className="btn" onClick={onClose}>
            关闭
          </button>
          <button className="btn primary" onClick={onResume}>
            恢复此会话
          </button>
        </>
      }
    >
      {error && <div style={{ color: 'var(--danger)' }}>{error}</div>}
      {!messages && !error && <div className="empty-hint">加载中…</div>}
      {messages && messages.length === 0 && <div className="empty-hint">没有可显示的内容</div>}
      {messages?.map((m, i) => (
        <div key={i} className={`preview-msg ${m.role}`}>
          {m.role !== 'tool' && <div className="preview-role">{ROLE_LABEL[m.role] ?? m.role}</div>}
          {m.role === 'tool' ? `> ${m.text}` : m.text}
        </div>
      ))}
    </Modal>
  )
}
