import { useEffect, useState } from 'react'
import type { TerminalTab } from '../types'
import { Modal } from './Modal'

interface Props {
  /** 处于等待输入状态的标签 */
  tabs: TerminalTab[]
  projectName: (path: string) => string
  onJump: (tab: TerminalTab) => void
  onClose: () => void
}

function waitText(since: number, now: number): string {
  const sec = Math.max(0, Math.floor((now - since) / 1000))
  if (sec < 60) return `${sec} 秒`
  if (sec < 3600) return `${Math.floor(sec / 60)} 分钟`
  return `${Math.floor(sec / 3600)} 小时 ${Math.floor((sec % 3600) / 60)} 分`
}

/** 待处理收件箱：集中列出所有等待输入的会话，等得最久的排最前 */
export function InboxDialog({ tabs, projectName, onJump, onClose }: Props) {
  const [now, setNow] = useState(Date.now())

  // 等待时长每秒走动
  useEffect(() => {
    const timer = setInterval(() => setNow(Date.now()), 1000)
    return () => clearInterval(timer)
  }, [])

  const sorted = [...tabs].sort((a, b) => a.statusSince - b.statusSince)

  return (
    <Modal
      title={`待处理（${tabs.length}）`}
      width={560}
      onClose={onClose}
      footer={<button className="btn" onClick={onClose}>关闭</button>}
    >
      {sorted.length === 0 && <div className="empty-hint">没有等待输入的会话</div>}
      {sorted.length > 0 && (
        <div className="row-list">
          {sorted.map((tab) => (
            <div key={tab.id} className="row">
              <span className="dot attention" />
              <div className="row-main">
                <div className="row-title">
                  {tab.title} <span className="badge">{projectName(tab.projectPath)}</span>{' '}
                  <span style={{ color: 'var(--warn)', fontSize: 12 }}>
                    已等待 {waitText(tab.statusSince, now)}
                  </span>
                </div>
                {tab.lastNotice && <div className="row-sub">{tab.lastNotice}</div>}
              </div>
              <div className="row-actions">
                <button className="btn small primary" onClick={() => onJump(tab)}>
                  前往
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </Modal>
  )
}
