'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import { type ChatMessage, generateMessageId } from '@/lib/protocol'
import { clearMessages, loadMessages, saveMessages } from '@/lib/chatStorage'

export function useChat(sessionId: string) {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [aiTyping, setAiTyping] = useState(false)

  // Track current sessionId to avoid stale saves
  const sessionIdRef = useRef(sessionId)
  sessionIdRef.current = sessionId

  // Load from localStorage when switching sessions
  useEffect(() => {
    setAiTyping(false)
    const cached = loadMessages(sessionId)
    setMessages(cached)
  }, [sessionId])

  // Persist to localStorage whenever messages change
  const messagesRef = useRef(messages)
  messagesRef.current = messages

  useEffect(() => {
    if (messages.length > 0) {
      saveMessages(sessionIdRef.current, messages)
    }
  }, [messages])

  const addMessage = useCallback((msg: ChatMessage) => {
    setMessages(prev => {
      if (prev.some(m => m.id === msg.id)) return prev
      return [...prev, msg]
    })
  }, [])

  const addMessages = useCallback((msgs: ChatMessage[]) => {
    setMessages(prev => {
      const existingIds = new Set(prev.map(m => m.id))
      const newMsgs = msgs.filter(m => !existingIds.has(m.id))
      if (newMsgs.length === 0) return prev
      return [...newMsgs, ...prev].sort((a, b) => a.timestamp - b.timestamp)
    })
  }, [])

  const clearAllMessages = useCallback(() => {
    setMessages([])
    setAiTyping(false)
    clearMessages(sessionId)
  }, [sessionId])

  const createUserMessage = useCallback(
    (text: string): ChatMessage => ({
      type: 'message',
      id: generateMessageId(),
      sessionId,
      from: 'user',
      text,
      timestamp: Date.now(),
    }),
    [sessionId],
  )

  return {
    messages,
    aiTyping,
    setAiTyping,
    addMessage,
    addMessages,
    createUserMessage,
    clearAllMessages,
  }
}
