import { MessageSquarePlus, Trash2 } from 'lucide-react'
import { useCallback, useEffect, useState } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'

import { Button } from '../../components/ui/button'
import type { Session } from '../../lib/types'
import { cn } from '../../lib/utils'
import { createSession, deleteSession, listSessions } from './api'

export function SessionList({ onNavigate }: { onNavigate?: () => void }) {
  const [sessions, setSessions] = useState<Session[]>([])
  const navigate = useNavigate()
  const { sessionId } = useParams()
  const isChat = useLocation().pathname.startsWith('/chat')

  const refresh = useCallback(async () => {
    if (!isChat) return
    const page = await listSessions()
    setSessions(page.items)
  }, [isChat])

  useEffect(() => {
    if (!isChat) return
    void listSessions().then((page) => setSessions(page.items))
    const listener = () => void refresh()
    window.addEventListener('kbqa:sessions-changed', listener)
    return () => window.removeEventListener('kbqa:sessions-changed', listener)
  }, [isChat, refresh])

  if (!isChat) return null

  async function addSession() {
    const session = await createSession()
    await refresh(); navigate(`/chat/${session.id}`); onNavigate?.()
  }
  async function removeSession(id: string) {
    if (!window.confirm('确定删除这个会话及全部历史吗？')) return
    await deleteSession(id); await refresh()
    if (sessionId === id) navigate('/chat')
  }

  return (
    <section className="session-rail">
      <Button className="new-session" size="sm" onClick={() => void addSession()}><MessageSquarePlus size={15} />新建会话</Button>
      <p className="nav-label">最近会话</p>
      <div className="session-list">
        {sessions.map((session) => <div key={session.id} className={cn('session-item', session.id === sessionId && 'session-item--active')}><button onClick={() => { navigate(`/chat/${session.id}`); onNavigate?.() }}><strong>{session.title || '新会话'}</strong><span>{new Date(session.updated_at).toLocaleDateString('zh-CN')}</span></button><Button variant="ghost" size="icon" title="删除会话" onClick={() => void removeSession(session.id)}><Trash2 size={13} /></Button></div>)}
        {sessions.length === 0 && <p className="session-empty">还没有历史会话</p>}
      </div>
    </section>
  )
}
