'use client'
import { request } from '@/http/request'
import { useCallback, useEffect, useState } from 'react';

export enum NovaState {
  Pending,
  Connected,
  Failed,
}

type UrlOverrides = {
  conversationId?: string
  agentId?: string
}

type ConversationIdentifiers = {
  agentId?: string
  conversationId?: string
}

const parseUrlOverrides = (search: string): UrlOverrides => {
  const params = new URLSearchParams(search)

  return {
    conversationId: params.get('conversationId') || undefined,
    agentId: params.get('agentId') || undefined,
  }
}

const resolveConversationIdentifiers = (
  res: { agent_id: string; conversation_id: string },
  overrides: UrlOverrides,
): ConversationIdentifiers => {
  const { conversationId: urlConversationId, agentId: urlAgentId } = overrides

  return {
    agentId: urlAgentId ?? res?.agent_id,
    conversationId: urlConversationId ?? res?.conversation_id,
  }
}

export const useBuildConversationConnect = () => {
  const [chatEnabled, setChatEnabled] = useState<NovaState>(NovaState.Pending)
  const [agentId, setAgentId] = useState<string>()
  const [conversationId, setConversationId] = useState<string>('')
  const [platformConfig, setPlatformConfig] = useState({
    wssUrl: '',
    apiBaseUrl: '',
    token: '',
    tenantId: '',
    agentId: '',
    agentName: '',
  })

  const connect = useCallback(async () => {
    try {
      const res = await request.get('/info')
      const search =
        typeof window === 'undefined' ? '' : window.location.search
      const urlOverrides = parseUrlOverrides(search)

      const { agentId: finalAgentId, conversationId: finalConversationId } =
        resolveConversationIdentifiers(res, urlOverrides)

      setAgentId(finalAgentId)
      setConversationId(finalConversationId ?? '')

      setPlatformConfig({
        wssUrl: res?.wssUrl,
        apiBaseUrl: res?.apiBaseUrl,
        token: res?.token,
        tenantId: res?.tenantId,
        agentId: finalAgentId ?? '',
        agentName: res?.agent_name ?? '',
      })
      setChatEnabled(NovaState.Connected)
    } catch {
      setChatEnabled(NovaState.Failed)
    }
  }, [])

  useEffect(() => {
    connect()
  }, [connect])

  return {
    chatEnabled,
    agentId,
    conversationId,
    platformConfig,
    connect,
  }
}