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 { getSessionAvatar } from '../utils/avatarUtils'

/** silent：不显示全屏「加载联系人」；失败时跳过更新 */
export type FetchContactsOptions = { silent?: boolean }

export function useContacts(
  token: string,
  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)
  const prevTokenRef = useRef<string | null>(null)

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

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

  // 退出登录或切换账号（token 变化）时清空联系人列表与当前会话，避免沿用上一账号的选中会话 id
  useEffect(() => {
    if (!token) {
      setContacts([])
      setActiveContactId(null)
      prevTokenRef.current = null
      return
    }
    if (prevTokenRef.current !== token) {
      prevTokenRef.current = token
      setContacts([])
      setActiveContactId(null)
    }
  }, [token, setActiveContactId])

  const fetchContacts = useCallback(async (options?: FetchContactsOptions) => {
    if (!token) return

    const silent = options?.silent === true
    if (!silent) {
      setIsLoadingContacts(true)
    }
    try {
      const contactsData = await api.getContacts(token)
      logger.info('App: Fetched contacts', { count: contactsData.length, silent })

      const formattedContacts: Contact[] = contactsData.map(contact => {
        const rawTime = contact.last_message_time
        const t =
          rawTime != null && rawTime !== ''
            ? new Date(rawTime).getTime()
            : undefined
        return {
          id: contact.id,
          name: contact.name || `用户${contact.id}`,
          avatar: getSessionAvatar(contact.id, contact.name, 40),
          lastMessage: contact.last_message,
          lastMessageTime: rawTime ? formatMessageTime(rawTime) : undefined,
          lastMessageAt: Number.isFinite(t) ? t : undefined,
          unreadCount: contact.unread_count ?? 0,
          remarks: contact.remarks ?? null
        }
      })

      setContacts(formattedContacts)

      if (formattedContacts.length > 0 && activeContactIdRef.current === null) {
        setActiveContactId(formattedContacts[0].id)
      }
    } catch (error: unknown) {
      if (silent) {
        logger.warn('App: fetchContacts skipped (silent)', {
          error: error instanceof Error ? error.message : String(error)
        })
      } else {
        logger.error('App: Failed to fetch contacts', {
          error: error instanceof Error ? error.message : String(error)
        })
      }
    } finally {
      if (!silent) {
        setIsLoadingContacts(false)
      }
    }
  }, [token, setActiveContactId])

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

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