import React, { useState } from 'react'
import ContactForm from './ContactForm'
import { Message, ChatConfig, ContactMethod } from '@/types'
import { useContactMethods } from '@/hooks/useContactMethods'
import { useLocalization } from '@/hooks/useLocalization'
// QR rendering is handled by QRModal via qrcode canvas
import QRModal from './QRModal'
import Avatar from './Avatar'

interface InteractiveMessageProps {
  message: Message
  config: ChatConfig
  onEmailSubmit?: (email: string) => void
  onWhatsAppClick?: () => void
}

const InteractiveMessage: React.FC<InteractiveMessageProps> = ({ 
  message, 
  config, 
  onEmailSubmit,
  onWhatsAppClick 
}) => {
  const [showContactForm, setShowContactForm] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const { getEnabledMethods } = useContactMethods()
  const { t } = useLocalization()
  const [qrState, setQrState] = useState<{ visible: boolean; title: string; value: string; hint?: string; imageUrl?: string; showQr?: boolean } | null>(null)

  const formatTime = (timestamp: Date) => {
    // Ensure timestamp is a valid Date object
    const date = timestamp instanceof Date ? timestamp : new Date(timestamp)
    if (isNaN(date.getTime())) {
      return '--:--'
    }
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  }

  // Removed unused handleEmailClick function

  const handleEmailSubmit = async (email: string) => {
    if (onEmailSubmit) {
      setIsSubmitting(true)
      try {
        await onEmailSubmit(email)
        setShowContactForm(false)
      } catch (error) {
        // Error handling will be managed by parent component
      } finally {
        setIsSubmitting(false)
      }
    }
  }

  const handleCancelContact = () => {
    setShowContactForm(false)
  }

  // Contact methods rendering
  const nonAIContactMethods = getEnabledMethods()
    .filter(method => method.type !== 'ai_chatbot')
    .filter(method => method.type !== 'contact_form')

  // Email is treated as a normal contact method; no standalone flag

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

  const handleMethodClick = async (method: ContactMethod) => {
    const { type, config: methodConfig, metadata } = method

    // WhatsApp special handling (keep logic, plus optional callback)
    if (type === 'whatsapp') {
      const isPremium = typeof window !== 'undefined' && (window as any).linkflowChat?.isPremium
      if (isPremium) {
        if (onWhatsAppClick) {
          onWhatsAppClick()
          return
        }
      }
      // Fallback: Open direct WhatsApp if a number or link is configured
      if (methodConfig?.phone) {
        const isGroupLink = String(methodConfig.phone).includes('chat.whatsapp.com')
        const url = isGroupLink
          ? String(methodConfig.phone)
          : `https://wa.me/${String(methodConfig.phone).replace(/[^0-9]/g, '')}`
        window.open(url, '_blank')
      }
      return
    }

    if (type === 'messenger') {
      if (methodConfig?.page_id) {
        const pageId: string = String(methodConfig.page_id).trim()
        const scheme = 'https://www.messenger.com/t/'
        window.open(`${scheme}${pageId}`, '_blank')
      }
      return
    }


    // Apple Messages special handling
    if (type === 'messages') {
      if (methodConfig?.apple_id) {
        const appleId: string = String(methodConfig.apple_id).trim()
        const isPhone = /^[+\d][\d\s\-().]*$/.test(appleId)
        const scheme = isPhone ? 'sms:' : 'imessage:'
        try {
          window.open(`${scheme}${appleId}`, '_self')
        } catch {
          if (!isPhone && /@/.test(appleId)) {
            window.open(`mailto:${appleId}`, '_self')
          }
        }
      }
      return
    }

    // Email method: prefer in-app contact form; fallback to mailto if available
    if (type === 'email') {
      if (onEmailSubmit) {
        setShowContactForm(true)
      } else if ((methodConfig as any)?.email) {
        window.open(`mailto:${(methodConfig as any).email}`, '_self')
      }
      return
    }

    // Email contact_form special case
    if (type === 'contact_form') {
      if (methodConfig?.email) {
        window.open(`mailto:${methodConfig.email}`, '_self')
      }
      return
    }

    // QR code display for certain platforms
    const showQRCode = async (title: string, value: string, hint?: string, imageUrl?: string) => {
      setQrState({ visible: true, title, value, hint, imageUrl, showQr: true })
      // QR rendering is handled inside QRModal via canvas now
    }

    if (type === 'line') {
      const lineId = String(methodConfig?.line_id || '')
      if (/^https?:\/\//i.test(lineId)) {
        window.open(lineId, '_blank')
      } else if (lineId) {
  showQRCode(metadata.name || 'LINE', `https://line.me/ti/p/${encodeURIComponent(lineId)}`, t('chat.scanToAdd', { platform: metadata.name || 'LINE' }))
      }
      return
    }

    if (type === 'wechat') {
      const wechatId = String(methodConfig?.wechat_id || '')
      if (/^https?:\/\//i.test(wechatId)) {
        window.open(wechatId, '_blank')
      } else if (wechatId) {
        showQRCode(
          metadata.name || 'WeChat',
          `http://weixin.qq.com/r/${encodeURIComponent(wechatId)}`,
          t('chat.scanToAdd', { platform: metadata.name || 'WeChat' })
        )
      }
      return
    }

    if (type === 'viber') {
      const phone = String(methodConfig?.phone || '')
      if (/^https?:\/\//i.test(phone)) {
        window.open(phone, '_blank')
      } else if (phone) {
  showQRCode(metadata.name || 'Viber', `viber://chat?number=${encodeURIComponent(phone)}`, t('chat.scanToChat', { platform: metadata.name || 'Viber' }))
      }
      return
    }

    // Call/SMS: show plain number
    if (type === 'call' || type === 'phone' || type === 'sms' || type === 'callback') {
      const phone = String(methodConfig?.phone || '')
      if (phone) {
  setQrState({ visible: true, title: metadata.name || 'Phone', value: phone, hint: t('chat.callOrSms'), showQr: false })
      }
      return
    }

    // Snapchat QR
    if (type === 'snapchat') {
      const username = String(methodConfig?.username || '')
      if (username) {
        const snapcode = `https://app.snapchat.com/web/deeplink/snapcode?username=${encodeURIComponent(username)}&type=PNG&size=512`
        const url = `https://www.snapchat.com/add/${encodeURIComponent(username)}`
        showQRCode('Snapchat', url, `@${username}`, snapcode)
      }
      return
    }

    // Generic rule: if config has absolute URL, open in new tab
    const possibleUrlKeys = ['url', 'link', 'channel_url', 'profile_url', 'team_link', 'server_invite', 'calendar_link']
    for (const key of possibleUrlKeys) {
      const value = (methodConfig as any)?.[key]
      if (typeof value === 'string' && /^https?:\/\//i.test(value)) {
        window.open(value, '_blank')
        return
      }
    }

    // Platform-specific builders
    if (type === 'telegram' && methodConfig?.username) {
      const username = String(methodConfig.username).replace('@', '').trim()
      window.open(`https://telegram.me/${username}`, '_blank')
      return
    }
    if (type === 'instagram' && methodConfig?.username) {
      const username = String(methodConfig.username).replace('@', '').trim()
      if (/^https?:\/\//i.test(username)) {
        window.open(username, '_blank')
        return
      }
      window.open(`https://instagram.com/${username}`, '_blank')
      return
    }
    if (type === 'x' && methodConfig?.username) {
      const username = String(methodConfig.username).replace('@', '').trim()
      window.open(`https://x.com/${username}`, '_blank')
      return
    }
    if (type === 'linkedin' && methodConfig?.profile_url) {
      window.open(String(methodConfig.profile_url), '_blank')
      return
    }
    if (type === 'youtube' && methodConfig?.channel_url) {
      window.open(String(methodConfig.channel_url), '_blank')
      return
    }
    if (type === 'discord' && methodConfig?.link) {
      window.open(String(methodConfig.link), '_blank')
      return
    }
    if (type === 'googlemaps' && methodConfig?.google_map_link) {
      const value = String(methodConfig.google_map_link)
      const url = /^https?:\/\//i.test(value) ? value : `https://www.google.com/maps/search/${encodeURIComponent(value)}`
      window.open(url, '_blank')
      return
    }
    if (type === 'kakaotalk' && methodConfig?.phone) {
      const id = String(methodConfig.phone)
      window.open(`https://open.kakao.com/o/${encodeURIComponent(id)}`, '_blank')
      return
    }
    if (type === 'skype' && methodConfig?.username) {
      const username = String(methodConfig.username).replace('@', '').trim()
      window.open(`skype:${username}?chat`, '_blank')
      return
    }

    if(type === 'tiktok' && methodConfig?.username) {
      const username = String(methodConfig.username).replace('@', '').trim()
      window.open(`https://www.tiktok.com/@${username}`, '_blank')
      return
    }
    if(type==='kakaotalk' && methodConfig?.chat_id) {
      const id = String(methodConfig.chat_id)
      // https://open.kakao.com/o/kwPeQEdW
      window.open(`https://open.kakao.com/o/${encodeURIComponent(id)}`, '_blank')
      return
    }
  }

  return (
    <div className="lfc-flex lfc-justify-start lfc-mb-6">
      <div className="lfc-max-w-xs sm:lfc-max-w-sm lfc-w-full">
        <div className="lfc-flex lfc-mb-1">
          <Avatar
            avatarUrl={config.avatarUrl}
            primaryColor={config.primaryColor}
            className="lfc-w-[38px] lfc-h-[38px] lfc-mr-2"
          />
           {/* Message content */}
        <div className="lfc-flex-1 lfc-bg-bg-layer lfc-text-text-primary lfc-border lfc-border-border-subtle lfc-rounded-lg lfc-px-3 lfc-py-2 lfc-break-words lfc-text-sm lfc-mb-3">
          {message.content}
        </div>
        </div>
        
       

        {/* Contact form or action buttons */}
        {showContactForm ? (
          <ContactForm
            onSubmit={handleEmailSubmit}
            onCancel={handleCancelContact}
            config={config}
            isLoading={isSubmitting}
            variant="compact"
          />
        ) : (
          <div className="lfc-space-y-3">
            <p className="lfc-text-xs lfc-text-text-secondary lfc-mb-1">{t('contact.chooseMethod')}</p>

            <div className="lfc-flex lfc-flex-wrap lfc-gap-2">
              {nonAIContactMethods.map((method, index) => (
                <button
                  key={`${method.type}-${index}`}
                  onClick={() => handleMethodClick(method)}
                  className="lfc-w-10 lfc-h-10 lfc-rounded-full lfc-flex lfc-items-center lfc-justify-center lfc-shadow hover:lfc-shadow-md lfc-transition"
                  title={method.buttonSettings?.hoverText || method.metadata.name}
                  style={{ backgroundColor: method.buttonSettings?.customColor || method.buttonSettings?.buttonColor || method.metadata.color }}
                >
                  {method.buttonSettings?.buttonImage ? (
                    <img
                      src={method.buttonSettings.buttonImage}
                      alt={method.metadata.name}
                      className="lfc-w-full lfc-h-full lfc-rounded-full lfc-object-cover"
                    />
                  ) : (
                    <img src={`${iconsBaseUrl}${method.metadata.icon}.svg`} alt={method.metadata.name} className="lfc-w-[80%] lfc-h-[80%]" title={method.buttonSettings?.hoverText || method.metadata.name} aria-label={method.buttonSettings?.hoverText || method.metadata.name} />
                  )}
                </button>
              ))}
            </div>
          </div>
        )}
        
        <div className="lfc-text-xs lfc-text-text-tertiary lfc-mt-1 lfc-text-left">
          {formatTime(message.timestamp)}
        </div>
        {qrState?.visible && (
          <QRModal
            title={qrState.title}
            iconUrl={`${iconsBaseUrl}${nonAIContactMethods.find(m=>m.metadata.name===qrState.title)?.metadata.icon || ''}.svg`}
            headerColor={
              nonAIContactMethods.find(m=>m.metadata.name===qrState.title)?.buttonSettings?.customColor ||
              nonAIContactMethods.find(m=>m.metadata.name===qrState.title)?.buttonSettings?.buttonColor ||
              nonAIContactMethods.find(m=>m.metadata.name===qrState.title)?.metadata.color
            }
            qrText={qrState.showQr && !qrState.imageUrl ? qrState.value : undefined}
            imageUrl={qrState.imageUrl}
            primaryText={qrState.value}
            emphasizePrimary={!qrState.showQr}
            ctaUrl={qrState.title === 'Viber' ? 'https://www.viber.com/download/' : undefined}
            ctaText={qrState.title === 'Viber' ? t('chat.openInDesktop', { platform: 'Viber' }) : undefined}
            onClose={() => setQrState(null)}
          />
        )}
      </div>
    </div>
  )
}

export default InteractiveMessage
 