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

interface BlockWidgetProps {
  serviceId: string
  config?: Partial<ChatConfig>
  buttonLabel?: string
  buttonStyle?: React.CSSProperties
  iconUrl?: string
  title?: string
  align?: 'left' | 'center' | 'right'
}

const BlockWidget: React.FC<BlockWidgetProps> = ({ serviceId, config = {}, buttonLabel = 'Chat', buttonStyle = {}, iconUrl, title, align = 'center' }) => {
  const buttonRef = useRef<HTMLDivElement>(null)
  const [forceAIWindow, setForceAIWindow] = React.useState(false)

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

  const { config: contactMethodsConfig } = useContactMethods()

  const handleSendMessage = async (message: string) => {
    try {
      clearError()
      setLoading(true)
      addMessage({ type: 'user', content: message })
      const effectiveServiceId = Number((aiService as any)?.service?.id || serviceId || 0) || undefined
      const response = await fetch(`${getApiUrl()}chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': (window as any).linkflowChat?.nonce || ''
        },
        body: JSON.stringify({
          message,
          conversationId: conversation?.id || null,
          pageUrl: typeof window !== 'undefined' ? window.location.href : '',
          serviceId: effectiveServiceId
        })
      })
      if (!response.ok) throw new Error(`HTTP ${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 || 'Failed to get response')
      }
    } finally {
      setLoading(false)
    }
  }

  const handleEmailSubmit = async (email: string) => {
    clearError()
    const response = await fetch(`${getApiUrl()}contact`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': (window as any).linkflowChat?.nonce || ''
      },
      body: JSON.stringify({ email, conversationId: conversation?.id, type: 'email' })
    })
    if (!response.ok) throw new Error(`HTTP ${response.status}`)
  }

  // When aiFirstReception is true: original AI chat; when false: overlay
  const useAIFirstReception = contactMethodsConfig?.aiFirstReception ?? false

  // Compute button visual to match editor: if icon provided use round icon; else use pill text button
  const renderTrigger = () => {
    const hasIcon = Boolean(iconUrl)
    if (hasIcon) {
      const baseSize = (() => {
        const fs = (buttonStyle as any)?.fontSize
        if (typeof fs === 'number') return Math.max(fs, 24)
        if (typeof fs === 'string') {
          const n = parseInt(fs, 10)
          return isNaN(n) ? 48 : Math.max(n, 24)
        }
        return 48
      })()
      return (
        <button
          type="button"
          className="lfc-w-12 lfc-h-12 lfc-rounded-full lfc-shadow hover:lfc-shadow-md lfc-transition lfc-flex lfc-items-center lfc-justify-center"
          style={{ width: baseSize, height: baseSize, backgroundColor: (buttonStyle.backgroundColor as string) || (config as any).primaryColor || '#3b82f6', color: (config as any).secondaryColor || '#ffffff', ...(buttonStyle || {}) }}
          onClick={isOpen ? closeChat : openChat}
          title={title || buttonLabel}
          aria-label={title || buttonLabel}
        >
          <img src={iconUrl!} alt={buttonLabel} className="lfc-w-[70%] lfc-h-[70%] lfc-rounded-full lfc-object-cover" />
        </button>
      )
    }
    // Text button
    const size = ((config as any).buttonSize || 'medium') as 'small' | 'medium' | 'large'
    const padding = size === 'small' ? '8px 14px' : size === 'large' ? '16px 26px' : '12px 20px'
    const fontSize = size === 'small' ? '13px' : size === 'large' ? '16px' : '14px'
    return (
      <a
        className="wp-block-button__link"
        style={{
          display: 'inline-block',
          textDecoration: 'none',
          background: (buttonStyle.backgroundColor as string) || (config as any).primaryColor || '#007cba',
          color: (buttonStyle.color as string) || (config as any).secondaryColor || '#ffffff',
          padding,
          fontSize,
          borderRadius: 6,
          width: (buttonStyle as any).width || undefined,
          textAlign: 'center',
          ...buttonStyle
        }}
        onClick={(e) => { e.preventDefault(); isOpen ? closeChat() : openChat() }}
        title={title || buttonLabel}
        aria-label={title || buttonLabel}
      >
        {buttonLabel || 'Chat'}
      </a>
    )
  }

  React.useEffect(() => {
    console.log('forceAIWindow', forceAIWindow)
  }, [forceAIWindow])

  return (
    <div className="linkflow-block-widget" id="linkflow-chat-tw-scope">
      <div ref={buttonRef} style={{ textAlign: align }}>
        {renderTrigger()}
      </div>

      {isOpen && (useAIFirstReception || forceAIWindow) && (
        <ChatWindow
          conversation={conversation}
          config={{ ...chatConfig, position: 'center' }}
          isLoading={isLoading}
          error={error}
          onClose={closeChat}
          onSendMessage={handleSendMessage}
          onEmailSubmit={handleEmailSubmit}
          aiName={aiService?.service?.showName}
          aiAvatarUrl={aiService?.service?.avatarUrl}
          buttonRef={buttonRef}
        />
      )}

      {isOpen && !useAIFirstReception && !forceAIWindow && (
        <ContactOverlay
          onClose={closeChat}
          onEmailSubmit={handleEmailSubmit}
          onAIChatbotClick={() => setForceAIWindow(true)}
          buttonRef={buttonRef}
          config={{ ...chatConfig, position: 'top-left' }}
        />
      )}
    </div>
  )
}

export default BlockWidget


