import React, { useEffect, useMemo, useRef, useState } from 'react'
import { ContactMethod, ChatConfig } from '@/types'
import { useContactMethods } from '@/hooks/useContactMethods'
import ContactForm from './ContactForm'
import QRModal from './QRModal'
import { useContactAction } from '@/hooks/useContactAction'

interface ContactOverlayProps {
  onClose: () => void
  onEmailSubmit?: (email: string) => void
  onWhatsAppClick?: (needConvLink: boolean) => void
  buttonRef: React.RefObject<HTMLDivElement>
  onAIChatbotClick?: () => void
  config: ChatConfig
}


const Button: React.FC<{ method: ContactMethod, handleMethodClick: (method: ContactMethod) => void, iconsBaseUrl: string }> = ({ method, handleMethodClick, iconsBaseUrl }) => {
  const bg = method.buttonSettings?.customColor || method.buttonSettings?.buttonColor || method.metadata.color
  const title = method.buttonSettings?.hoverText || method.metadata.name
  return (
    <button
      className="lfc-w-12 lfc-h-12 lfc-rounded-full lfc-flex lfc-items-center lfc-justify-center lfc-shadow hover:lfc-shadow-md lfc-transition"
      onClick={() => handleMethodClick(method)}
      title={title}
      style={{ backgroundColor: bg }}
    >
      {method.buttonSettings?.buttonImage ? (
        <img src={method.buttonSettings.buttonImage} alt={title} className="lfc-w-full lfc-h-full lfc-rounded-full lfc-object-cover" />
      ) : (
        <img src={`${iconsBaseUrl}${method.metadata.icon}.svg`} alt={title} className="lfc-w-[70%] lfc-h-[70%]" />
      )}
    </button>
  )
}


const ContactOverlay: React.FC<ContactOverlayProps> = ({ onClose, onEmailSubmit, onWhatsAppClick, buttonRef, onAIChatbotClick, config }) => {
  const { getEnabledMethods } = useContactMethods()
  const containerRef = useRef<HTMLDivElement>(null)

  const iconsBaseUrl: string = (typeof window !== 'undefined' && (window as any).linkflowChat?.iconsBaseUrl) || ''

  const enabledMethods: ContactMethod[] = useMemo(() => {
    return getEnabledMethods().filter(m => m.type !== 'contact_form')
  }, [getEnabledMethods])


  const [overlayStyle, setOverlayStyle] = useState<React.CSSProperties>({})

  useEffect(() => {
    const positionOverlay = () => {
      if (config.position === 'center') {
        const style: React.CSSProperties = {
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)'
        }
        setOverlayStyle(style)
        return
      }
      if (!buttonRef.current) return
      const buttonRect = buttonRef.current.getBoundingClientRect()
      const windowWidth = window.innerWidth
      const windowHeight = window.innerHeight
      const gap = 20
      const overlayWidth = 320 // w-80

      const style: React.CSSProperties = { position: 'fixed' }

      switch (config.position) {
        case 'bottom-right':
          style.bottom = `${windowHeight - buttonRect.top + gap}px`
          style.right = `${windowWidth - buttonRect.left - buttonRect.width}px`
          break
        case 'bottom-left':
          style.bottom = `${windowHeight - buttonRect.top + gap}px`
          style.left = `${buttonRect.left}px`
          break
        case 'top-right':
          style.top = `${buttonRect.bottom + gap}px`
          style.right = `${windowWidth - buttonRect.left - buttonRect.width}px`
          break
        case 'top-left':
          style.top = `${buttonRect.bottom + gap}px`
          style.left = `${buttonRect.right - buttonRect.width}px`
          break
        default:
          style.bottom = `${windowHeight - buttonRect.top + gap}px`
          style.right = `${windowWidth - buttonRect.left - buttonRect.width}px`
          break
      }

      if (style.left && parseFloat(style.left as string) < 0) {
        style.left = '8px'
      }
      if (style.right && parseFloat(style.right as string) < 0) {
        style.right = '8px'
      }
      if (style.top && parseFloat(style.top as string) < 0) {
        style.top = '8px'
      }
      if (style.bottom && parseFloat(style.bottom as string) < 0) {
        style.bottom = '8px'
      }

      if (style.left) {
        const leftValue = parseFloat(style.left as string)
        if (leftValue + overlayWidth > windowWidth) {
          style.left = `${windowWidth - overlayWidth - 8}px`
        }
      }

      setOverlayStyle(style)
    }
    positionOverlay()
    window.addEventListener('resize', positionOverlay)
    return () => window.removeEventListener('resize', positionOverlay)
  }, [buttonRef, config.position])

  const getVisibilityClasses = () => {
    const classes: string[] = []
    if (classes.length === 0) classes.push('lfc-flex lfc-flex-col')
    return classes.join(' ')
  }

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (!containerRef.current) return
      if (!(e.target instanceof Node)) return
      // Ignore clicks on the floating chat button itself to avoid double toggle
      if (buttonRef.current && buttonRef.current.contains(e.target)) {
        return
      }
      if (!containerRef.current.contains(e.target)) {
        onClose()
      }
    }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [onClose])

  const [showContactForm, setShowContactForm] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const resolvedPrimaryColor = (typeof window !== 'undefined' && (window as any).linkflowChat?.serviceConfig?.data?.appearance?.primaryColor) || '#3b82f6'

  const effectiveConfig: ChatConfig = {
    position: 'bottom-right',
    buttonSize: 'medium',
    primaryColor: resolvedPrimaryColor,
    showOnMobile: true,
    showOnDesktop: true
  } as ChatConfig

  const handleEmailFormSubmit = async (email: string) => {
    if (!onEmailSubmit) return
    setIsSubmitting(true)
    try {
      await onEmailSubmit(email)
      setShowContactForm(false)
    } finally {
      setIsSubmitting(false)
    }
  }

  const { handleMethodClick: handleContactAction, qrState, closeQr } = useContactAction({
    onWhatsAppClick: (/* needConvLink */) => { if (onWhatsAppClick) onWhatsAppClick(false) },
    onEmailFormRequest: () => setShowContactForm(true),
  })

  const handleMethodClick = async (method: ContactMethod) => {
    if (method.type === 'ai_chatbot') {
      if (onAIChatbotClick) onAIChatbotClick()
      return
    }
    handleContactAction(method)
  }



  // Only render methods explicitly enabled in admin (no implicit AI injection)
  const methodsToRender: ContactMethod[] = useMemo(() => enabledMethods, [enabledMethods])
  return (
    <div ref={containerRef} className={`lfc-fixed lfc-z-40 lfc-bg-white lfc-rounded-xl lfc-shadow-xl lfc-border lfc-border-border-subtle lfc-p-3 lfc-w-80 ${getVisibilityClasses()}`}
         style={overlayStyle}
    >
      <div className="lfc-grid lfc-grid-cols-5 lfc-gap-3">
        {methodsToRender.map((m, idx) => (
          <Button key={`${m.type}-${idx}`} method={m} 
            handleMethodClick={handleMethodClick}
            iconsBaseUrl={iconsBaseUrl}
          />
        ))}
      </div>

      {showContactForm && (
        <div className="lfc-mt-3">
          <ContactForm
            onSubmit={handleEmailFormSubmit}
            onCancel={() => setShowContactForm(false)}
            config={effectiveConfig}
            isLoading={isSubmitting}
            variant="compact"
          />
        </div>
      )}
      {qrState?.visible && (
        <QRModal
          title={qrState.title}
          iconUrl={qrState.iconUrl}
          headerColor={qrState.headerColor}
          qrText={qrState.qrText}
          imageUrl={qrState.imageUrl}
          primaryText={qrState.primaryText}
          emphasizePrimary={qrState.emphasizePrimary}
          ctaUrl={qrState.ctaUrl}
          ctaText={qrState.ctaText}
          onClose={closeQr}
        />
      )}
      {/* <div className="lfc-flex lfc-justify-end lfc-mt-3">
        <button onClick={onClose} aria-label="Close" className="lfc-w-10 lfc-h-10 lfc-rounded-full lfc-flex lfc-items-center lfc-justify-center lfc-bg-gray-100 hover:lfc-bg-gray-200">
          <svg className="lfc-w-5 lfc-h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div> */}
    </div>
  )
}

export default ContactOverlay


