import { useCallback, useMemo, useState } from "react"
import type { WorkspaceSummary } from "@qjclaw/shared-types"
import { EMPTY_SESSION_ID } from "../../lib/constants"
import { resolvePreferredSessionId } from "../../lib/chat-utils"

export function useProjectSessions() {
  const [sessions, setSessions] = useState<WorkspaceSummary["sessions"]>([])
  const [activeSessionId, setActiveSessionId] = useState(EMPTY_SESSION_ID)

  const preferredSessionId = useMemo(
    () => resolvePreferredSessionId(sessions, activeSessionId),
    [activeSessionId, sessions]
  )
  const visibleSessionId = useMemo(
    () => activeSessionId || preferredSessionId,
    [activeSessionId, preferredSessionId]
  )

  const clearSessions = useCallback(() => {
    setSessions([])
    setActiveSessionId(EMPTY_SESSION_ID)
  }, [])

  const openSession = useCallback((sessionId: string) => {
    setActiveSessionId(sessionId)
  }, [])

  const upsertSession = useCallback((session: WorkspaceSummary["sessions"][number]) => {
    setSessions((current) => [session, ...current.filter((item) => item.id !== session.id)])
  }, [])

  return {
    sessions,
    activeSessionId,
    preferredSessionId,
    visibleSessionId,
    setSessions,
    setActiveSessionId,
    clearSessions,
    openSession,
    upsertSession
  }
}
