import React, { useRef } from 'react'
import ChatButton from './ChatButton'
import ChatWindow from './ChatWindow'
import ContactOverlay from './ContactOverlay'
import { useChatManager } from '@/hooks/useChatManager'
import { useContactMethods } from '@/hooks/useContactMethods'
import { ChatConfig } from '@/types'
import { useLocalization } from '@/hooks/useLocalization'
import { getApiUrl } from '@/utils'

interface ChatWidgetProps {
  serviceId: string
  config?: Partial<ChatConfig>
  autoOpen?: boolean
}

const ChatWidget: React.FC<ChatWidgetProps> = ({ serviceId, config = {}, autoOpen = false }) => {
  const buttonRef = useRef<HTMLDivElement>(null)
  const [forceAIWindow, setForceAIWindow] = React.useState(false)

  const {
    isOpen,
    isLoading,
    conversation,
    config: chatConfig,
    error,
    openChat,
    closeChat,
    addMessage,
    clearError,
    setLoading,
    getTokenByConversationId,
    aiService
  } = useChatManager({
    serviceId,
    initialConfig: config
  })

  const {
    config: contactMethodsConfig,
    getEnabledMethods
  } = useContactMethods()

  const { t } = useLocalization()
  // Auto-open support (for core/button variation trigger)
  React.useEffect(() => {
    if (autoOpen) {
      // Slight delay to ensure mount completes
      const id = setTimeout(() => {
        openChat()
      }, 0)
      return () => clearTimeout(id)
    }
  }, [autoOpen])

  // Reset forced AI window when closed
  React.useEffect(() => {
    if (!isOpen && forceAIWindow) {
      setForceAIWindow(false)
    }
  }, [isOpen, forceAIWindow])

  // 获取nonce用于API调用
  const getNonce = () => {
    if (typeof window !== 'undefined') {
      if ((window as any).linkflowChatConfig) {
        return (window as any).linkflowChatConfig.nonce || ''
      }
      if ((window as any).linkflowChat) {
        return (window as any).linkflowChat.nonce || ''
      }
    }
    return ''
  }

  // Removed legacy handleSendMessage (we now use inline wrapper to ensure serviceId)

  const handleEmailSubmit = async (email: string) => {
    try {
      clearError()

      // 构建邮件转发请求
      const requestBody = {
        email: email,
        conversationId: conversation?.id,
        type: 'email'
      }

      // 实际API调用
      const response = await fetch(`${getApiUrl()}contact`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': getNonce()
        },
        body: JSON.stringify(requestBody)
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const data = await response.json()

      if (data.success) {
        addMessage({
          type: 'system',
          content: t('chat.emailSentSuccess', { email })
        })
      } else {
        const errorMessage = data.error?.message || t('chat.failedToSendEmail')
        throw new Error(errorMessage)
      }

    } catch (err) {
      console.error('Error sending email:', err)
      throw err
    }
  }

  const handleWhatsAppClick = async (needConvLink: boolean = true) => {
    try {
      clearError()

      // 如果没有会话ID，先创建会话
      let conversationId = conversation?.id
      // 验证conversationId是否为有效ID（支持字符串和数字）
      if (!conversationId || (typeof conversationId === 'number' && conversationId <= 0) || (typeof conversationId === 'string' && conversationId.trim() === '')) {
        // 没有有效会话ID，直接跳转 WhatsApp，不带聊天记录链接
        jumpToWhatsApp()
        return
      }

      // 确保conversationId是字符串类型
      const conversationIdStr = String(conversationId);

      // 生成临时页面URL
      // 先通过conversationId获取临时token
      let tempUrl = ''
      if (needConvLink) {
        try {
          const tokenData = await getTokenByConversationId(conversationIdStr);
          if (tokenData && tokenData.token) {
            tempUrl = `${getApiUrl()}history/${tokenData.token}`
          }
        } catch (e) {
          // 获取 token 失败，忽略，继续跳转 WhatsApp
        }
      }


      jumpToWhatsApp(tempUrl)
    } catch (err) {
      console.error('Error opening WhatsApp:', err)
      // 错误处理由 useChatManager 内部处理
    }

    // 跳转 WhatsApp 的辅助函数
    function jumpToWhatsApp(tempUrl?: string) {
      // 优先从已启用的联系方式中随机选择一个 WhatsApp 账号
      const enabledMethods = typeof getEnabledMethods === 'function' ? getEnabledMethods() : []
      const whatsappCandidates = (enabledMethods || []).filter(m => m.type === 'whatsapp' && m.config && m.config.phone)

      // 有聊天记录链接时带 text，无则不带 text
      const hasTempUrl = !!tempUrl
      const messageText = hasTempUrl ? `${t('chat.whatsappMessage')} ${tempUrl}` : ''

      if (whatsappCandidates.length > 0) {
        const randomIndex = Math.floor(Math.random() * whatsappCandidates.length)
        const chosen = whatsappCandidates[randomIndex]
        const rawPhone = String(chosen.config.phone)
        const isGroupLink = rawPhone.includes('chat.whatsapp.com')
        if (isGroupLink) {
          // 群链接直接打开（群邀请链接一般不支持预填消息）
          window.open(rawPhone, '_blank')
        } else {
          const waNumber = rawPhone.replace(/[^0-9]/g, '')
          const waUrl = `https://wa.me/${waNumber}`
          if (hasTempUrl) {
            const fullUrl = `${waUrl}?text=${encodeURIComponent(messageText)}`
            window.open(fullUrl, '_blank')
          } else {
            window.open(waUrl, '_blank')
          }
        }
      } else {
        // 回退到全局配置 URL（兼容旧逻辑）
        const globalConfig = (typeof window !== 'undefined' && (window as any).linkflowChat) ? (window as any).linkflowChat : {}
        const whatsappUrl = globalConfig.whatsappUrl || 'https://wa.me/1234567890'
        if (hasTempUrl) {
          const fullWhatsAppUrl = `${whatsappUrl}?text=${encodeURIComponent(messageText)}`
          window.open(fullWhatsAppUrl, '_blank')
        } else {
          window.open(whatsappUrl, '_blank')
        }
      }
    }
  }


  // Determine behavior
  // When aiFirstReception is true: preserve existing behavior (AI chat window)
  // When false: clicking button shows an overlay with all contact channels
  const useAIFirstReception = contactMethodsConfig?.aiFirstReception ?? false



  // Keep button appearance customizable per-page, but do not affect window styling
  const buttonConfig = {
    ...chatConfig,
    position: config.position || chatConfig.position,
    buttonSize: config.buttonSize || chatConfig.buttonSize,
    primaryColor: config.primaryColor ?? chatConfig.primaryColor,
    secondaryColor: config.secondaryColor ?? chatConfig.secondaryColor,
    buttonShiftHorizontal: config.buttonShiftHorizontal ?? chatConfig.buttonShiftHorizontal,
    buttonShiftVertical: config.buttonShiftVertical ?? chatConfig.buttonShiftVertical,
    showOnMobile: config.showOnMobile ?? chatConfig.showOnMobile,
    showOnDesktop: config.showOnDesktop ?? chatConfig.showOnDesktop,
    zIndex: config.zIndex ?? chatConfig.zIndex,
    buttonImage: config.buttonImage ?? chatConfig.buttonImage,
  }

  const windowConfig = { ...chatConfig }

  // Resolve effective serviceId to send with chat API
  const getEffectiveServiceId = () => {
    const fromHook = (aiService as any)?.service?.id
    if (fromHook && Number(fromHook) > 0) return Number(fromHook)
    const fromGlobal = (typeof window !== 'undefined' && (window as any).linkflowChat?.serviceConfig?.data?.service?.id) || undefined
    if (fromGlobal && Number(fromGlobal) > 0) return Number(fromGlobal)
    if (serviceId && Number(serviceId) > 0) return Number(serviceId)
    return undefined
  }

  if (!getEffectiveServiceId() && !getEnabledMethods?.()?.length) {
    return null
  }

  if(!useAIFirstReception && !getEnabledMethods?.()?.length) {
    return null
  }


  return (
    <div className="chat-widget" id="linkflow-chat-tw-scope">
      {/* Chat Button */}
      {!(buttonConfig.showOnMobile === false && buttonConfig.showOnDesktop === false) && (
        <ChatButton
          isOpen={isOpen}
          onClick={() => {
            if (isOpen) {
              setForceAIWindow(false)
              closeChat()
            } else {
              openChat()
            }
          }}
          config={buttonConfig}
          ref={buttonRef}
        />
      )}

      {/* Conditional Window Rendering */}
      {isOpen && (useAIFirstReception || forceAIWindow) && (
        <ChatWindow
          conversation={conversation}
          config={windowConfig}
          isLoading={isLoading}
          error={error}
          onClose={closeChat}
          onSendMessage={async (message) => {
            // Wrapper to ensure serviceId is included
            try {
              clearError()
              setLoading(true)
              addMessage({ type: 'user', content: message })
              const requestBody = {
                message,
                conversationId: conversation?.id || null,
                pageUrl: typeof window !== 'undefined' ? window.location.href : '',
                serviceId: getEffectiveServiceId(),
              }
              const response = await fetch(`${getApiUrl()}chat`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': getNonce() },
                body: JSON.stringify(requestBody)
              })
              if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
              const data = await response.json()
              if (data.success) {
                if (data.data.needsTransfer) {
                  addMessage({ type: 'interactive', content: data.data.message || '', metadata: { transferOptions: data.data.transferOptions || [] } })
                } else {
                  addMessage({ type: 'ai', content: data.data.message })
                }
              } else {
                throw new Error(data.error?.message || t('chat.failedToGetAIResponse'))
              }
            } catch (err) {
              console.error('Error sending message:', err)
            } finally {
              setLoading(false)
            }
          }}
          onEmailSubmit={handleEmailSubmit}
          onWhatsAppClick={handleWhatsAppClick}
          aiName={aiService?.service?.showName}
          aiAvatarUrl={aiService?.service?.avatarUrl}
          buttonRef={buttonRef}
        />
      )}

      {/* Contact overlay when AI First Reception is OFF */}
      {isOpen && !useAIFirstReception && !forceAIWindow && (
        <ContactOverlay
          onClose={closeChat}
          onEmailSubmit={handleEmailSubmit}
          onWhatsAppClick={handleWhatsAppClick}
          onAIChatbotClick={() => setForceAIWindow(true)}
          buttonRef={buttonRef}
          config={windowConfig}
        />
      )}
    </div>
  )
}

export default ChatWidget