import { useState, useEffect, useRef, useCallback } from 'react'
import { Contact } from '../types'
import { api } from '../services/api'
import { logger } from '../utils/logger'
import { formatMessageTime } from '../utils/timeUtils'
import { getDefaultAvatar } from '../utils/avatarUtils'

export function useContacts(
  token: string,
  unreadCountsRef: React.MutableRefObject<Record<number, number>>,
  activeContactId: number | null,
  setActiveContactId: (id: number | null) => void
) {
  const [contacts, setContacts] = useState<Contact[]>([])
  const [isLoadingContacts, setIsLoadingContacts] = useState(false)
  const contactsRef = useRef<Contact[]>([])
  const activeContactIdRef = useRef(activeContactId)

  useEffect(() => {
    contactsRef.current = contacts
  }, [contacts])

  useEffect(() => {
    activeContactIdRef.current = activeContactId
  }, [activeContactId])

  const fetchContacts = useCallback(async () => {
    if (!token) return
    
    setIsLoadingContacts(true)
    try {
      const contactsData = await api.getContacts(token)
      logger.info('App: Fetched contacts', { count: contactsData.length })
      
      const formattedContacts: Contact[] = contactsData.map(contact => ({
        id: contact.id,
        name: contact.name || `用户${contact.id}`,
        avatar: getDefaultAvatar(contact.id, contact.name),
        lastMessage: contact.last_message,
        lastMessageTime: contact.last_message_time ? formatMessageTime(contact.last_message_time) : undefined,
        unreadCount: unreadCountsRef.current[contact.id] || 0
      }))
      
      setContacts(formattedContacts)
      
      if (formattedContacts.length > 0 && activeContactIdRef.current === null) {
        setActiveContactId(formattedContacts[0].id)
      }
    } catch (error: any) {
      logger.error('App: Failed to fetch contacts', { error: error.message })
    } finally {
      setIsLoadingContacts(false)
    }
  }, [token, unreadCountsRef, setActiveContactId])

  useEffect(() => {
    if (token) {
      fetchContacts()
    }
  }, [token, fetchContacts])

  return {
    contacts,
    setContacts,
    contactsRef,
    isLoadingContacts,
    fetchContacts
  }
}
