import React from 'react'
import ReactDOM from 'react-dom/client'
import ChatWidget from './components/ChatWidget'
import BlockWidget from './components/BlockWidget'
import type { ServiceConfig } from '@/types'
import './index.css'

// Initialize chat widgets
function initializeChatWidgets() {
  // Find all chat widget containers (legacy)
  // const containers = document.querySelectorAll('.linkflow-chat-widget')
  // containers.forEach((container) => {
  //   const serviceId = container.getAttribute('data-service-id')
  //   // const config = container.getAttribute('data-config')

  //   if (serviceId) {
  //     // const root = ReactDOM.createRoot(container)
  //     // root.render(
  //     //   <React.StrictMode>
  //     //     <ChatWidget
  //     //       serviceId={serviceId}
  //     //       config={config ? JSON.parse(config) : {}}
  //     //       autoOpen={false}
  //     //     />
  //     //   </React.StrictMode>
  //     // )
  //   }
  // })

  // Find all block containers
  const blockContainers = document.querySelectorAll('.linkflow-chat-block')

  blockContainers.forEach((container) => {    
    const serviceConfig = (window as any).linkflowChat?.serviceConfig
    type ServiceConfigWithGlobal = ServiceConfig & { globalDisplay?: { enabled: boolean; mobileEnabled: boolean; zIndex: number } }
    const data = serviceConfig?.data as ServiceConfigWithGlobal | undefined

    const serviceId = (container.getAttribute('data-service-id') || (data?.service?.id ? String(data.service.id) : '') || '1')

    {
      const config = {
        position: 'center' as const,
        buttonSize: (container.getAttribute('data-button-size') || 'medium') as 'small' | 'medium' | 'large',
        primaryColor: (container.getAttribute('data-custom-color') || '') || container.getAttribute('data-primary-color') || '#007cba',
        secondaryColor: container.getAttribute('data-text-color') || '#ffffff',
      }
      const label = container.getAttribute('data-button-label') || 'Chat'
      const fullWidth = container.getAttribute('data-full-width') === 'true'
      const customColor = container.getAttribute('data-custom-color') || ''
      const buttonImage = container.getAttribute('data-button-image') || ''
      const hoverText = container.getAttribute('data-hover-text') || ''
      const alignRaw = container.getAttribute('data-align') || 'center'
      const align = (alignRaw === 'left' || alignRaw === 'right' || alignRaw === 'center') ? alignRaw : 'center'

      // fine-grained values
      const paddingVertical = Number(container.getAttribute('data-padding-vertical') || '0')
      const paddingHorizontal = Number(container.getAttribute('data-padding-horizontal') || '0')
      const borderWidth = Number(container.getAttribute('data-border-width') || '0')
      const borderColor = container.getAttribute('data-border-color') || config.primaryColor
      const borderRadius = Number(container.getAttribute('data-border-radius') || '6')
      const variant = (container.getAttribute('data-variant') || 'fill') as 'fill' | 'outline'
      const customSize = Number(container.getAttribute('data-custom-size') || '0')

      const style: React.CSSProperties = {}
      if (customColor) style.backgroundColor = customColor
      if (fullWidth) style.width = '100%'
      if (borderWidth) style.borderWidth = borderWidth
      if (borderColor) style.borderColor = borderColor
      if (borderRadius) style.borderRadius = borderRadius
      if (variant === 'outline') {
        style.backgroundColor = 'transparent'
        if (!borderWidth) style.borderWidth = 1
        if (!style.borderColor) style.borderColor = config.primaryColor
        style.borderStyle = 'solid'
      }
      if (borderWidth && !style.borderStyle) style.borderStyle = 'solid'
      if (customSize) style.fontSize = customSize
      if (paddingVertical || paddingHorizontal) style.padding = `${paddingVertical}px ${paddingHorizontal}px`
      if (config.secondaryColor) style.color = config.secondaryColor

      const root = ReactDOM.createRoot(container)
      root.render(
        <React.StrictMode>
          <div style={{ textAlign: align as any }}>
            <BlockWidget
              serviceId={serviceId}
              config={config}
              buttonLabel={label}
              buttonStyle={style}
              iconUrl={buttonImage || undefined}
              title={hoverText || undefined}
              align={align as any}
            />
          </div>
        </React.StrictMode>
      )
    }
  })

  // Initialize global display widgets only if no block is present
  if (blockContainers.length === 0) {
    initializeGlobalDisplayWidget()
  }
}

// Initialize global display widget
async function initializeGlobalDisplayWidget() {
  // Check if there's a global widget container
  const globalContainer = document.getElementById('linkflow-chat-global-widget')

  if (!globalContainer) {
    return
  }

  try {
    const serviceConfig = (window as any).linkflowChat?.serviceConfig
    type ServiceConfigWithGlobal = ServiceConfig & { globalDisplay?: { enabled: boolean; mobileEnabled: boolean; zIndex: number } }
    const data = serviceConfig?.data as ServiceConfigWithGlobal | undefined

    if (!serviceConfig || !serviceConfig.success || !data) {
      globalContainer.style.display = 'none'
      return
    }

    const serviceId = data.service?.id

    // Check device compatibility
    const isMobile = window.innerWidth <= 768
    const mobileEnabled = data.globalDisplay?.mobileEnabled ?? true
    if (isMobile && !mobileEnabled) {
      globalContainer.style.display = 'none'
      return
    }

    const position = (data.appearance?.buttonPosition || 'bottom-right') as 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left' | 'center'
    const appearance = data.appearance

    const config = {
      position,
      primaryColor: appearance?.primaryColor || '#007cba',
      secondaryColor: appearance?.secondaryColor || '#ffffff',
      buttonSize: (appearance?.buttonSize || 'medium') as 'small' | 'medium' | 'large',
      buttonShiftHorizontal: appearance?.buttonShiftHorizontal || 0,
      buttonShiftVertical: appearance?.buttonShiftVertical || 0,
      buttonImage: appearance?.buttonImage || '',
      showOnMobile: mobileEnabled,
      showOnDesktop: true,
      zIndex: data.globalDisplay?.zIndex ?? 9999,
      showName: data.service?.showName,
      avatarUrl: data.service?.avatarUrl
    }

    const root = ReactDOM.createRoot(globalContainer)
    root.render(
      <React.StrictMode>
        <ChatWidget
          serviceId={String(serviceId)}
          config={config}
        />
      </React.StrictMode>
    )

  } catch (error) {
    console.error('LinkFlow Chat: Failed to initialize global widget:', error)
    globalContainer.style.display = 'none'
  }
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', initializeChatWidgets)

// Handle window resize for responsive behavior
window.addEventListener('resize', () => {
  try {
    const globalContainer = document.getElementById('linkflow-chat-global-widget')
    if (globalContainer && globalContainer.style.display !== 'none') {
      initializeGlobalDisplayWidget()
    }
  } catch (e) {
    // no-op
  }
});

// Global function for block initialization (called from PHP)

(window as any).linkflowChatInit = function (containerId: string, config: any) {


  const container = document.getElementById(containerId)

  if (!container) {
    console.error('LinkFlow Chat: Container not found:', containerId)
    return
  }

  if (!config.serviceId || config.serviceId === 0) {
    console.error('LinkFlow Chat: Invalid service ID:', config.serviceId)
    return
  }



  const typedConfig = {
    position: config.position as 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left' | 'center',
    buttonSize: config.buttonSize as 'small' | 'medium' | 'large',
    primaryColor: config.primaryColor,
    secondaryColor: config.secondaryColor,
    buttonShiftHorizontal: config.buttonShiftHorizontal || 0,
    buttonShiftVertical: config.buttonShiftVertical || 0,
    showOnMobile: config.showOnMobile,
    showOnDesktop: config.showOnDesktop,
    buttonImage: config.buttonImage || ''
  }

  try {
    const root = ReactDOM.createRoot(container)
    root.render(
      <React.StrictMode>
        <ChatWidget
          serviceId={config.serviceId.toString()}
          config={typedConfig}
          autoOpen={!!config.autoOpen}
        />
      </React.StrictMode>
    )
  } catch (error) {
    console.error('LinkFlow Chat: Error rendering widget:', error)
  }
}

// Expose a simple global method to open chat on demand
;(window as any).linkflowOpenChat = function(options?: { serviceId?: string | number, autoOpen?: boolean, position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left' | 'center' }) {
  try {
    // Get backend configuration
    const serviceConfig = (window as any).linkflowChat?.serviceConfig
    type ServiceConfigWithGlobal = ServiceConfig & { globalDisplay?: { enabled: boolean; mobileEnabled: boolean; zIndex: number } }
    const data = serviceConfig?.data as ServiceConfigWithGlobal | undefined
    const appearance = data?.appearance

    // Build config with backend theme colors
    const chatConfig = {
      position: (options?.position || 'center') as any,
      primaryColor: appearance?.primaryColor || '#007cba',
      secondaryColor: appearance?.secondaryColor || '#ffffff',
      buttonSize: (appearance?.buttonSize || 'medium') as 'small' | 'medium' | 'large',
      buttonImage: appearance?.buttonImage || '',
      showOnDesktop: false,
      showOnMobile: false,
      zIndex: 9999,
      showName: data?.service?.showName,
      avatarUrl: data?.service?.avatarUrl
    }

    // Try to find existing global widget container; otherwise create a temporary centered widget
    const existing = document.getElementById('linkflow-chat-global-widget')
    if (existing) {
      // If already rendered with React, we can dispatch a custom event that ChatWidget listens to in the future.
      // Fallback: simulate click on the button by toggling a data-flag and re-mounting.
      const root = ReactDOM.createRoot(existing)
      const serviceId = existing.getAttribute('data-service-id') || (options?.serviceId ? String(options.serviceId) : '')
      root.render(
        <React.StrictMode>
          <ChatWidget
            serviceId={serviceId}
            config={chatConfig}
            autoOpen={true}
          />
        </React.StrictMode>
      )
      return
    }

    // Create an ephemeral container in center
    const tempId = 'linkflow-chat-temp-' + Math.random().toString(36).slice(2)
    const container = document.createElement('div')
    container.id = tempId
    container.className = 'linkflow-chat-widget'
    container.setAttribute('data-mode', 'temp')
    document.body.appendChild(container)
    const root = ReactDOM.createRoot(container)
    const globalServiceId = (window as any).linkflowChat?.serviceConfig?.data?.service?.id
    const finalServiceId = String(options?.serviceId || globalServiceId || '')
    root.render(
      <React.StrictMode>
        <ChatWidget
          serviceId={finalServiceId}
          config={chatConfig}
          autoOpen={true}
        />
      </React.StrictMode>
    )
  } catch (e) {
    console.error('LinkFlow Chat: Failed to open chat', e)
  }
}

function setupCoreButtonDelegation() {
  const handler = (e: Event) => {
    try {
      const target = e.target as HTMLElement
      if (!target) return
      // Ignore clicks inside the mounted chat widget to avoid re-mounting it
      if (target.closest('.chat-widget') || target.closest('#linkflow-chat-global-widget') || target.closest('.linkflow-chat-widget')) {
        return
      }
      const wrapper = target.closest('[data-linkflow-chat="true"]') as HTMLElement | null
      if (!wrapper) return
      const anchor = target.closest('a')
      if (anchor) {
        e.preventDefault()
        e.stopPropagation()
      }
      const serviceId = wrapper.getAttribute('data-service-id') || undefined
      ;(window as any).linkflowOpenChat({ serviceId, position: 'center', autoOpen: true })
    } catch (err) {
      // no-op
    }
  }
  document.addEventListener('click', handler, true)
}

document.addEventListener('DOMContentLoaded', setupCoreButtonDelegation)