import { useEffect, useMemo, useState } from 'react'
import { Clock, Search, Trash2, X } from 'lucide-react'
import { filterConversations } from '../services/chatHistory.js'

function relativeTime(ts) {
  const diff = Date.now() - ts
  const seconds = Math.floor(diff / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`

  const d = new Date(ts)
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${month}-${day}`
}

export default function HistoryDrawer({ open, onClose, conversations, onSelect, onDelete }) {
  const [query, setQuery] = useState('')
  const filtered = useMemo(
    () => filterConversations(conversations || [], query),
    [conversations, query]
  )

  useEffect(() => {
    if (!open) return
    const onKeyDown = (event) => {
      if (event.key === 'Escape') onClose?.()
    }
    window.addEventListener('keydown', onKeyDown)
    return () => window.removeEventListener('keydown', onKeyDown)
  }, [open, onClose])

  return (
    <>
      {/* 遮罩 */}
      <div
        aria-hidden={!open}
        className={`fixed inset-0 z-40 bg-black/20 transition-opacity duration-200 ${
          open ? 'opacity-100' : 'opacity-0 pointer-events-none'
        }`}
        onClick={onClose}
      />
      {/* 抽屉 */}
      <div
        aria-hidden={!open}
        className={`fixed top-0 right-0 z-50 h-full w-72 bg-white border-l border-gray-200 flex flex-col transition-transform duration-200 ${
          open ? 'translate-x-0' : 'translate-x-full pointer-events-none'
        }`}
      >
        {/* Header */}
        <div className="flex-shrink-0 border-b border-gray-100 px-4 py-3">
          <div className="flex items-center gap-2">
            <Clock size={16} className="text-gray-400" />
            <span className="text-sm font-medium text-gray-700">历史会话</span>
            <span className="ml-auto text-[11px] text-gray-400">{conversations?.length || 0}</span>
            <button
              onClick={onClose}
              className="w-6 h-6 grid place-items-center rounded-full text-gray-400 hover:bg-gray-100 hover:text-gray-600"
              title="关闭"
            >
              <X size={13} />
            </button>
          </div>
          <div className="mt-3 relative">
            <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400" />
            <input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="搜索标题、内容或会话 ID"
              className="w-full h-8 pl-8 pr-8 text-[12px] rounded-lg border border-gray-200 bg-gray-50 focus:bg-white focus:outline-none focus:border-brand-400"
            />
            {query && (
              <button
                onClick={() => setQuery('')}
                className="absolute right-2 top-1/2 -translate-y-1/2 w-5 h-5 grid place-items-center rounded-full text-gray-400 hover:bg-gray-100 hover:text-gray-600"
                title="清空搜索"
              >
                <X size={12} />
              </button>
            )}
          </div>
        </div>

        {/* List */}
        <div className="flex-1 overflow-y-auto">
          {(!conversations || conversations.length === 0) ? (
            <div className="flex items-center justify-center h-full text-sm text-gray-400">
              暂无历史记录
            </div>
          ) : filtered.length === 0 ? (
            <div className="flex items-center justify-center h-full text-sm text-gray-400">
              没有匹配结果
            </div>
          ) : (
            <div className="py-2">
              {filtered.map(conv => (
                <div
                  key={conv.id}
                  className="group px-4 py-3 hover:bg-gray-50 cursor-pointer flex items-start justify-between gap-2"
                  onClick={() => onSelect(conv)}
                >
                  <div className="flex-1 min-w-0">
                    <div className="text-sm text-gray-800 font-medium truncate">
                      {conv.skillName || '新对话'}
                    </div>
                    <div className="text-xs text-gray-400 truncate mt-0.5">
                      {conv.preview || '无内容'}
                    </div>
                    <div className="text-xs text-gray-300 mt-1">
                      {relativeTime(conv.updatedAt)}
                    </div>
                  </div>
                  <button
                    className="opacity-0 group-hover:opacity-100 flex-shrink-0 w-6 h-6 flex items-center justify-center rounded hover:bg-red-50 text-gray-300 hover:text-red-400 transition-opacity"
                    onClick={(e) => {
                      e.stopPropagation()
                      onDelete(conv.id)
                    }}
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </>
  )
}
