import { useState, useCallback, useEffect, useRef } from 'react'
import { useChatStore } from '../store/useChatStore'
import type { Message } from '../store/useChatStore'


export interface ConversationItem {
  id: string
  title: string
  preview: string
  createdAt: string
  updatedAt: string
}

interface BackendMessage {
  id: string
  conversationId: string
  role: string
  content: string
  createdAt: string
}

export function useConversations() {
  const [conversations, setConversations] = useState<ConversationItem[]>([])
  const [activeId, setActiveId] = useState<string | null>(null)
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [error, setError] = useState<string | null>(null)

  const setConversationId = useChatStore((s) => s.setConversationId)
  const setMessages = useChatStore((s) => s.setMessages)

  const fetchConversations = useCallback(async () => {
    setIsLoading(true)
    setError(null)
    try {
      const res = await fetch('/api/v1/conversations')
      if (!res.ok) {
        throw new Error(`Failed to fetch conversations: ${res.statusText}`)
      }
      const data: ConversationItem[] = await res.json()
      setConversations(data)
      return data
    } catch (err: any) {
      console.error('[useConversations] fetchConversations error:', err)
      setError(err.message || 'Error fetching conversations')
      return []
    } finally {
      setIsLoading(false)
    }
  }, [])

  const loadMessages = useCallback(async (conversationId: string) => {
    try {
      const res = await fetch(`/api/v1/conversations/${conversationId}/messages`)
      if (!res.ok) {
        throw new Error(`Failed to fetch messages: ${res.statusText}`)
      }
      const rawMessages: BackendMessage[] = await res.json()
      const formattedMessages: Message[] = rawMessages.map((m) => ({
        id: m.id,
        role: m.role.toLowerCase() === 'user' ? 'user' : 'agent',
        content: m.content,
        createdAt: m.createdAt,
      }))
      setMessages(formattedMessages)
    } catch (err: any) {
      console.error('[useConversations] loadMessages error:', err)
      setMessages([])
    }
  }, [setMessages])

  const deleteConversation = useCallback(async (id: string) => {
    try {
      await fetch(`/api/v1/conversations/${id}`, { method: 'DELETE' })
      setConversations((prev) => prev.filter((c) => c.id !== id))
    } catch (err: any) {
      console.error('[useConversations] deleteConversation error:', err)
    }
  }, [])

  const updateTitle = useCallback(async (id: string, newTitle: string) => {
    try {
      const res = await fetch(`/api/v1/conversations/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: newTitle }),
      })
      if (!res.ok) throw new Error('Failed to update title')
      const updated: ConversationItem = await res.json()
      setConversations((prev) =>
        prev.map((c) => (c.id === id ? { ...c, title: updated.title } : c))
      )
      return true
    } catch (err: any) {
      console.error('[useConversations] updateTitle error:', err)
      return false
    }
  }, [])

  const selectConversation = useCallback(async (id: string) => {
    const currentMessages = useChatStore.getState().messages
    if (activeId && activeId !== id && currentMessages.length === 0) {
      deleteConversation(activeId)
    }

    setActiveId(id)
    setConversationId(id)
    await loadMessages(id)
  }, [activeId, setConversationId, loadMessages, deleteConversation])

  const createNewConversation = useCallback(async () => {
    const currentMessages = useChatStore.getState().messages
    if (activeId && currentMessages.length === 0) {
      return conversations.find((c) => c.id === activeId) || null
    }

    setIsLoading(true)
    try {
      const res = await fetch('/api/v1/conversations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      })
      if (!res.ok) {
        throw new Error(`Failed to create conversation: ${res.statusText}`)
      }
      const newConv: ConversationItem = await res.json()
      const newItem: ConversationItem = {
        id: newConv.id,
        title: 'Cuộc trò chuyện mới',
        preview: '',
        createdAt: newConv.createdAt,
        updatedAt: newConv.updatedAt,
      }
      setConversations((prev) => [newItem, ...prev])
      setActiveId(newConv.id)
      setConversationId(newConv.id)
      setMessages([])
      return newItem
    } catch (err: any) {
      console.error('[useConversations] createNewConversation error:', err)
      setError(err.message || 'Error creating conversation')
      return null
    } finally {
      setIsLoading(false)
    }
  }, [activeId, conversations, setConversationId, setMessages])

  const initRef = useRef(false)

  // Initial load
  useEffect(() => {
    if (initRef.current) return
    initRef.current = true

    fetchConversations().then((items) => {
      if (items && items.length > 0) {
        selectConversation(items[0].id)
      } else {
        createNewConversation()
      }
    })
  }, [])

  return {
    conversations,
    activeId,
    isLoading,
    error,
    fetchConversations,
    selectConversation,
    createNewConversation,
    deleteConversation,
    updateTitle,
  }
}

