/**
 * useChatFilter — gerencia toda a lógica de filtro/escopo de chats no inbox.
 *
 * Extrai de inbox/index.tsx:
 *  - searchTerm, activeFilter, chatScope, favoriteJids
 *  - derivados: favoriteSet, filterCounts, chatsByScope, isFavoriteChat
 */
import { useState, useMemo, useCallback } from 'react'
import { normalizeJid } from '../../utils/inboxUtils'
import type { NewWhatsChat } from '../../types/inboxTypes'

export type ChatScope = 'inbox' | 'favorites' | 'archived'

export interface CustomChatList { id: string; name: string; jids: string[] }

export function useChatFilter(chatsStore: NewWhatsChat[]) {
  const [searchTerm,         setSearchTerm]         = useState('')
  const [activeFilter,       setActiveFilter]        = useState('all')
  const [chatScope,          setChatScope]           = useState<ChatScope>('inbox')
  const [favoriteJids,       setFavoriteJids]        = useState<string[]>([])
  const [customLists,        setCustomLists]         = useState<CustomChatList[]>([])
  const [activeCustomListId, setActiveCustomListId]  = useState<string | null>(null)

  // ── Derivados ──────────────────────────────────────────────────────────────

  const favoriteSet = useMemo(() => new Set(favoriteJids), [favoriteJids])

  const filterCounts = useMemo(() => ({
    all:      chatsStore.length,
    unread:   chatsStore.filter(c => c.unread_count > 0).length,
    groups:   chatsStore.filter(c => c.remote_jid.endsWith('@g.us')).length,
    pinned:   chatsStore.filter(c => c.is_pinned).length,
    archived: chatsStore.filter(c => c.is_archived).length,
  }), [chatsStore])

  const chatsByScope = useMemo(() => {
    let base = chatsStore
    if (chatScope === 'favorites') {
      base = base.filter(c => favoriteSet.has(normalizeJid(c.remote_jid) || c.remote_jid))
    } else if (chatScope === 'archived') {
      base = base.filter(c => Boolean(c.is_archived))
    } else {
      base = base.filter(c => !Boolean(c.is_archived))
    }

    if (activeFilter === 'unread')  return base.filter(c => c.unread_count > 0)
    if (activeFilter === 'groups')  return base.filter(c => c.remote_jid.endsWith('@g.us'))
    if (activeFilter === 'pinned')  return base.filter(c => c.is_pinned)
    return base
  }, [chatScope, chatsStore, favoriteSet, activeFilter])

  const isFavoriteChat = useCallback(
    (chat: NewWhatsChat) => favoriteSet.has(normalizeJid(chat.remote_jid) || chat.remote_jid),
    [favoriteSet]
  )

  const toggleFavorite = useCallback((jid: string) => {
    const normalized = normalizeJid(jid) || jid
    setFavoriteJids(prev =>
      prev.includes(normalized) ? prev.filter(j => j !== normalized) : [...prev, normalized]
    )
  }, [])

  return {
    // Estado
    searchTerm,
    activeFilter,
    chatScope,
    favoriteJids,
    customLists,
    activeCustomListId,

    // Setters
    setSearchTerm,
    setActiveFilter,
    setChatScope,
    setCustomLists,
    setActiveCustomListId,

    // Derivados
    favoriteSet,
    filterCounts,
    chatsByScope,
    isFavoriteChat,
    toggleFavorite,
  }
}
