import { Bot, CircleAlert, UserRound } from 'lucide-react'

import type { Message, Source } from '../../lib/types'

function AnswerContent({ content, sources, onSource }: { content: string; sources: Source[]; onSource: (source: Source, sources: Source[]) => void }) {
  const lookup = new Map(sources.map((source) => [source.label, source]))
  return <p className="answer-copy">{content.split(/(\[S\d+])/g).map((part, index) => {
    const label = part.match(/^\[(S\d+)]$/)?.[1]
    const source = label ? lookup.get(label) : undefined
    if (!label) return <span key={index}>{part}</span>
    if (!source) return <span key={index} className="citation citation--deleted">来源已删除</span>
    return <button key={index} className="citation" onClick={() => onSource(source, sources)}>{label}</button>
  })}</p>
}

type Props = { messages: Message[]; onSource: (source: Source, sources: Source[]) => void }

export function MessageList({ messages, onSource }: Props) {
  if (messages.length === 0) return <div className="chat-empty"><div><Bot size={28} /></div><p className="eyebrow">STRICT KNOWLEDGE MODE</p><h2>从有出处的答案开始</h2><span>系统会先让研究 Agent 检索资料，再由主 Agent 组织回答。</span></div>
  return (
    <div className="message-list">
      {messages.map((message) => <article key={message.id} className={`message message--${message.role}`}>
        <div className="message-avatar">{message.role === 'user' ? <UserRound size={15} /> : <Bot size={15} />}</div>
        <div className="message-body"><header><strong>{message.role === 'user' ? '你' : '知识库助手'}</strong><time>{new Date(message.created_at).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}</time></header>{message.status === 'failed' ? <p className="failed-message"><CircleAlert size={14} />回答生成失败，可重新发送问题。</p> : message.role === 'assistant' ? <AnswerContent content={message.content} sources={message.sources} onSource={onSource} /> : <p>{message.content}</p>}</div>
      </article>)}
    </div>
  )
}
