import { useState } from 'react'
import { searchSessions } from '../ipc'
import type { Config, SearchHit } from '../types'
import { PreviewDialog } from './PreviewDialog'
import { IconSearch } from './Icons'

interface Props {
  config: Config
  onResume: (projectPath: string, sessionId: string, title: string) => void
}

/** 跨项目搜索会话内容 */
export function SearchPage({ config, onResume }: Props) {
  const [query, setQuery] = useState('')
  const [scope, setScope] = useState('')
  const [hits, setHits] = useState<SearchHit[] | null>(null)
  const [searching, setSearching] = useState(false)
  const [preview, setPreview] = useState<SearchHit | null>(null)

  const run = async () => {
    if (!query.trim()) return
    setSearching(true)
    try {
      setHits(await searchSessions(scope || null, query.trim()))
    } finally {
      setSearching(false)
    }
  }

  const projectName = (path: string) =>
    config.projects.find((p) => p.path === path)?.name ?? path

  return (
    <div className="page">
      <h2>搜索会话</h2>
      <p className="page-desc">在会话记录的对话文本中搜索（大小写不敏感，每个会话显示首条命中）</p>
      <div className="toolbar">
        <select className="select" value={scope} onChange={(e) => setScope(e.target.value)}>
          <option value="">全部项目</option>
          {config.projects.map((p) => (
            <option key={p.path} value={p.path}>
              {p.name}
            </option>
          ))}
        </select>
        <input
          className="input"
          style={{ flex: 1, maxWidth: 420 }}
          placeholder="搜索内容"
          value={query}
          autoFocus
          onChange={(e) => setQuery(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') void run()
          }}
        />
        <button className="btn primary" disabled={searching || !query.trim()} onClick={() => void run()}>
          <IconSearch />
          {searching ? '搜索中…' : '搜索'}
        </button>
      </div>
      {hits && (
        <div className="row-list">
          {hits.length === 0 && <div className="empty-hint">没有命中</div>}
          {hits.map((h) => (
            <div key={`${h.projectPath}:${h.sessionId}`} className="row">
              <div className="row-main">
                <div className="row-title">
                  {config.titleOverrides[h.sessionId] ?? h.title}{' '}
                  <span className="badge">{projectName(h.projectPath)}</span>
                </div>
                <div className="row-sub">{h.snippet}</div>
              </div>
              <div className="row-actions">
                <button className="btn small" onClick={() => setPreview(h)}>
                  预览
                </button>
                <button
                  className="btn small primary"
                  onClick={() => onResume(h.projectPath, h.sessionId, h.title)}
                >
                  恢复
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
      {preview && (
        <PreviewDialog
          projectPath={preview.projectPath}
          sessionId={preview.sessionId}
          title={preview.title}
          onClose={() => setPreview(null)}
          onResume={() => {
            onResume(preview.projectPath, preview.sessionId, preview.title)
            setPreview(null)
          }}
        />
      )}
    </div>
  )
}
