/**
 * useInstanceSelector — gerencia seleção e troca de instâncias WhatsApp.
 *
 * Extrai toda a lógica de instâncias do inbox/index.tsx.
 * O componente visual consome apenas as variáveis retornadas.
 */
import { useRef, useCallback, useMemo, useEffect } from 'react'
import { useInstanceStore } from '../../store/instanceStore'
import { useChatStore } from '../../store/chatStore'
import { socketService } from '../../services/socketService'

// ─── Tipos ────────────────────────────────────────────────────────────────────

export interface LegacyInstance {
  instance: string
  nome: string
  status: string
  phone: string | null
  avatar: null
  profilePictureUrl: null
}

export interface MappedInstance {
  id: string
  nome: string
  avatar: null
  phone: string | null
}

// ─── Hook ─────────────────────────────────────────────────────────────────────

export function useInstanceSelector() {
  const instances      = useInstanceStore((s) => s.instances)
  const activeId       = useInstanceStore((s) => s.activeInstanceId)
  const setActiveId    = useInstanceStore((s) => s.setActiveInstance)
  const loadInstances  = useInstanceStore((s) => s.loadInstances)
  const connectInstance = useInstanceStore((s) => s.connectInstance)
  const qrByInstance   = useInstanceStore((s) => s.qrByInstance)

  const resetChats     = useChatStore((s) => s.setChats)

  const dropdownRef = useRef<HTMLDivElement>(null)

  // ── Formato legado esperado pelo JSX do inbox ──────────────────────────────

  const instancesLegacy = useMemo<LegacyInstance[]>(() =>
    instances.map((i) => ({
      instance: i.id,
      nome: i.name,
      status: i.status === 'CONNECTED' ? 'connected' : i.status.toLowerCase(),
      phone: i.phone,
      avatar: null,
      profilePictureUrl: null,
    })),
    [instances]
  )

  const activeInstance = useMemo<LegacyInstance | null>(
    () => instancesLegacy.find((i) => i.instance === activeId) ?? null,
    [instancesLegacy, activeId]
  )

  // Versão com `id` usada por alguns componentes internos
  const mappedActiveInstance = useMemo<MappedInstance | null>(
    () => activeInstance
      ? { id: activeInstance.instance, nome: activeInstance.nome, avatar: null, phone: activeInstance.phone }
      : null,
    [activeInstance]
  )

  // Apenas instâncias conectadas (para o dropdown de troca rápida)
  const connectedInstances = useMemo<MappedInstance[]>(() =>
    instances
      .filter((i) => i.status === 'CONNECTED')
      .map((i) => ({ id: i.id, nome: i.name, avatar: null, phone: i.phone })),
    [instances]
  )

  const isConnected = activeInstance?.status === 'connected'

  // ── Auto-select primeira instância disponível ──────────────────────────────

  useEffect(() => {
    if (!activeId && instances.length > 0) {
      const first = instances[0]
      setActiveId(first.id)
      socketService.joinInstance(first.id)
    }
  }, [instances, activeId, setActiveId])

  // ── Troca de instância ────────────────────────────────────────────────────

  const selectInstance = useCallback((legacyInstance: LegacyInstance | { instance: string }) => {
    const id = legacyInstance.instance
    if (id === activeId) return
    resetChats([])
    setActiveId(id)
    socketService.joinInstance(id)
  }, [activeId, setActiveId, resetChats])

  // ── Refresh ────────────────────────────────────────────────────────────────

  const refreshInstances = useCallback(async () => {
    await loadInstances()
  }, [loadInstances])

  const handleConnect = useCallback(async (instanceId: string) => {
    await connectInstance(instanceId)
  }, [connectInstance])

  return {
    // Estado
    instances: instancesLegacy,
    activeInstance,
    mappedActiveInstance,
    connectedInstances,
    isConnected,
    qrByInstance,
    activeInstanceId: activeId,

    // Refs (para click-outside no dropdown)
    dropdownRef,

    // Handlers
    selectInstance,
    refreshInstances,
    handleConnect,
  }
}
