'use client'

import { useEffect, useState } from 'react'
import { MessageCircle, X,  Bot } from 'lucide-react'
import AiChatbot from './AiChatbot'

interface ContactInfo {
  institute: {
    name: {
      english: string
    }
  }
  contactMethods: {
    socialMedia: {
      whatsapp: string
    }
    phone: string[]
    email: string[]
  }
  officeHours: {
    regular: string
  }
}

type ContactOption = 'whatsapp' | 'call' | 'email' | 'chatbot'

export default function WhatsAppIcon() {
  const [contactData, setContactData] = useState<ContactInfo | null>(null)
  const [whatsappNumber, setWhatsappNumber] = useState('+8801873515482')
  const [isOpen, setIsOpen] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [showNotification, setShowNotification] = useState(true)
  const [showChatbot, setShowChatbot] = useState(false)

  useEffect(() => {
    const fetchContactInfo = async () => {
      try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/contact-info`)
        const data = await response.json()
        
        if (data.success && data.data) {
          const contactInfo: ContactInfo = data.data
          setContactData(contactInfo)
          
          // Extract WhatsApp number
          let number = '+8801873515482' // Default number
          
          // Check WhatsApp URL first
          const whatsappUrl = contactInfo.contactMethods?.socialMedia?.whatsapp
          if (whatsappUrl) {
            const match = whatsappUrl.match(/wa\.me\/(.+)/)
            if (match && match[1]) {
              number = match[1]
            }
          }
          
          // If no WhatsApp URL, check phone numbers
          if (number === '+8801873515482' && contactInfo.contactMethods?.phone?.length > 0) {
            number = contactInfo.contactMethods.phone[0]
          }
          
          // Format the number
          const formattedNumber = formatWhatsAppNumber(number)
          setWhatsappNumber(formattedNumber)
        }
      } catch (error) {
        console.error('Error fetching contact info:', error)
      } finally {
        setIsLoading(false)
      }
    }

    fetchContactInfo()
  }, [])

  const formatWhatsAppNumber = (number: string): string => {
    let cleanNumber = number.replace(/[^\d+]/g, '')
    
    if (cleanNumber.startsWith('+88')) return cleanNumber
    if (cleanNumber.startsWith('88')) return `+${cleanNumber}`
    if (!cleanNumber.startsWith('+') && !cleanNumber.startsWith('88')) {
      if (cleanNumber.startsWith('0')) cleanNumber = cleanNumber.substring(1)
      return `+88${cleanNumber}`
    }
    
    return '+8801873515482'
  }

  const handleContactClick = (option: ContactOption) => {
    switch (option) {
      case 'whatsapp':
        const message = "Hello! I'm interested in learning more about Noore Resalat Model Madrasah. Could you please provide me with more information?"
        const encodedMessage = encodeURIComponent(message)
        const whatsappUrl = `https://wa.me/${whatsappNumber}?text=${encodedMessage}`
        window.open(whatsappUrl, '_blank', 'noopener,noreferrer')
        break
        
      case 'call':
        window.open(`tel:${whatsappNumber.replace('+', '')}`, '_self')
        break
        
      case 'email':
        const email = contactData?.contactMethods?.email?.[0] || 'info@nrmm.com'
        window.open(`mailto:${email}`, '_self')
        break
        
      case 'chatbot':
        setShowChatbot(true)
        break
    }
    
    setIsOpen(false)
  }

  const contactOptions = [
    {
      id: 'chatbot' as ContactOption,
      icon: Bot,
      label: 'AI Assistant',
      color: 'bg-purple-600 hover:bg-purple-700',
      iconBg: 'bg-purple-700 group-hover:bg-purple-800',
      delay: 'delay-0'
    },
    
    {
      id: 'whatsapp' as ContactOption,
      icon: MessageCircle,
      label: 'WhatsApp',
      color: 'bg-green-600 hover:bg-green-700',
      iconBg: 'bg-green-700 group-hover:bg-green-800',
      delay: 'delay-100'
    },
    
  ]

  if (isLoading) {
    return (
      <div className="fixed bottom-6 right-6 z-[999999]">
        <div className="animate-pulse">
          <div className="w-14 h-14 bg-gradient-to-br from-green-500 to-green-600 rounded-full flex items-center justify-center shadow-2xl border-2 border-white">
            <MessageCircle className="w-6 h-6 text-white" />
          </div>
        </div>
      </div>
    )
  }

  return (
    <>
      {/* AI Chatbot Modal */}
      {showChatbot && (
        <div className="fixed inset-0 z-[999999] bg-black/50 flex items-center justify-center p-4 animate-in fade-in-0 duration-200">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl h-[80vh] animate-in zoom-in-95 duration-300">
            <div className="flex justify-between items-center p-4 border-b">
              <h3 className="text-lg font-semibold text-gray-800">AI Assistant</h3>
              <button 
                onClick={() => setShowChatbot(false)}
                className="p-2 hover:bg-gray-100 rounded-full transition-colors"
              >
                <X className="w-5 h-5 text-gray-600" />
              </button>
            </div>
            <div className="h-[calc(80vh-80px)]">
              <AiChatbot onClose={() => setShowChatbot(false)} />
            </div>
          </div>
        </div>
      )}

      {/* Main Floating Widget */}
      <div className="fixed bottom-6 right-6 z-[999999]">
        {/* Welcome Notification */}
        {showNotification && !isOpen && !showChatbot && (
          <div className="absolute bottom-20 right-0 bg-gradient-to-r from-green-600 to-green-700 text-white p-2 rounded-md shadow-2xl w-72 animate-in fade-in-0 slide-in-from-right-4 mb-4">
            <div className="flex items-start gap-3">
              <div className="flex-1">
  <h4 className="font-semibold text-xs mb-1">সাহায্য প্রয়োজন?</h4>
  <p className="text-[11px] text-green-100 mb-2">
    ভর্তি ও প্রোগ্রাম সম্পর্কিত তাত্ক্ষণিক সহায়তার জন্য আমাদের AI সহকারীকে জিজ্ঞেস করুন, কল করুন বা মেসেজ করুন।
  </p>
  <p className="text-[9px] text-green-200">
    অফিস সময়: {contactData?.officeHours?.regular || '৯:১৫ AM - ২:৩০ PM'}
  </p>
</div>

              <button 
                onClick={() => setShowNotification(false)}
                className="text-green-200 hover:text-white transition-colors flex-shrink-0"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
            <div className="absolute -bottom-2 right-6 w-4 h-4 bg-green-600 rotate-45"></div>
          </div>
        )}

        {/* Expanded Contact Options */}
        {isOpen && (
          <div className="absolute bottom-16 right-0 mb-4 space-y-2 animate-in fade-in-0 zoom-in-95 duration-200">
            {contactOptions.map((option) => (
              <button
                key={option.id}
                onClick={() => handleContactClick(option.id)}
                className={`
                  flex items-center gap-3 text-white px-4 py-3 rounded-full shadow-2xl 
                  transition-all duration-200 group animate-in slide-in-from-right-4 
                  hover:scale-105 ${option.color} ${option.delay}
                `}
              >
                <div className={`p-1 rounded-full transition-colors ${option.iconBg}`}>
                  <option.icon className="w-4 h-4" />
                </div>
                <span className="text-sm font-medium whitespace-nowrap">{option.label}</span>
              </button>
            ))}
          </div>
        )}

        {/* Main Floating Button */}
        <button
          onClick={() => setIsOpen(!isOpen)}
          className={`
            relative w-14 h-14 rounded-full shadow-2xl transition-all duration-300 
            flex items-center justify-center border-2 border-white
            ${
              isOpen 
                ? 'bg-gradient-to-br from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 rotate-45 scale-110' 
                : 'bg-gradient-to-br from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 hover:scale-110'
            }
          `}
        >
          {isOpen ? (
            <X className="w-6 h-6 text-white" />
          ) : (
            <MessageCircle className="w-6 h-6 text-white" />
          )}
          
          {/* Ping Animation */}
          {!isOpen && !showChatbot && (
            <div className="absolute inset-0 rounded-full bg-green-400 animate-ping opacity-75 -z-10"></div>
          )}

          {/* Online Status Dot */}
          <div className="absolute -top-1 -right-1 w-4 h-4 bg-green-400 border-2 border-white rounded-full animate-pulse"></div>
        </button>

        {/* Tooltip */}
        {!isOpen && !showChatbot && (
          <div className="absolute bottom-14 right-0 bg-gray-900 text-white text-xs px-3 py-2 rounded-lg shadow-lg whitespace-nowrap animate-in fade-in-0 zoom-in-95 mb-2">
            Contact Support
            <div className="absolute -bottom-1 right-6 w-2 h-2 bg-gray-900 rotate-45"></div>
          </div>
        )}
      </div>
    </>
  )
}


















// 'use client'

// import { useEffect, useState } from 'react'
// import { MessageCircle, X, Bot } from 'lucide-react'

// interface ContactInfo {
//   institute: {
//     name: {
//       english: string
//     }
//   }
//   contactMethods: {
//     socialMedia: {
//       whatsapp: string
//     }
//     phone: string[]
//     email: string[]
//   }
//   officeHours: {
//     regular: string
//   }
// }

// type ContactOption = 'whatsapp' | 'call' | 'email' | 'chatbot'

// export default function WhatsAppIcon() {
//   const [contactData, setContactData] = useState<ContactInfo | null>(null)
//   const [whatsappNumber, setWhatsappNumber] = useState('+8801873515482')
//   const [isOpen, setIsOpen] = useState(false)
//   const [isLoading, setIsLoading] = useState(true)
//   const [showNotification, setShowNotification] = useState(true)
//   const [showChatbotPopup, setShowChatbotPopup] = useState(false)

//   useEffect(() => {
//     const fetchContactInfo = async () => {
//       try {
//         const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/contact-info`)
//         const data = await response.json()
        
//         if (data.success && data.data) {
//           const contactInfo: ContactInfo = data.data
//           setContactData(contactInfo)
          
//           // Extract WhatsApp number
//           let number = '+8801873515482' // Default number
          
//           // Check WhatsApp URL first
//           const whatsappUrl = contactInfo.contactMethods?.socialMedia?.whatsapp
//           if (whatsappUrl) {
//             const match = whatsappUrl.match(/wa\.me\/(.+)/)
//             if (match && match[1]) {
//               number = match[1]
//             }
//           }
          
//           // If no WhatsApp URL, check phone numbers
//           if (number === '+8801873515482' && contactInfo.contactMethods?.phone?.length > 0) {
//             number = contactInfo.contactMethods.phone[0]
//           }
          
//           // Format the number
//           const formattedNumber = formatWhatsAppNumber(number)
//           setWhatsappNumber(formattedNumber)
//         }
//       } catch (error) {
//         console.error('Error fetching contact info:', error)
//       } finally {
//         setIsLoading(false)
//       }
//     }

//     fetchContactInfo()
//   }, [])

//   const formatWhatsAppNumber = (number: string): string => {
//     let cleanNumber = number.replace(/[^\d+]/g, '')
    
//     if (cleanNumber.startsWith('+88')) return cleanNumber
//     if (cleanNumber.startsWith('88')) return `+${cleanNumber}`
//     if (!cleanNumber.startsWith('+') && !cleanNumber.startsWith('88')) {
//       if (cleanNumber.startsWith('0')) cleanNumber = cleanNumber.substring(1)
//       return `+88${cleanNumber}`
//     }
    
//     return '+8801873515482'
//   }

//   const handleContactClick = (option: ContactOption) => {
//     switch (option) {
//       case 'whatsapp':
//         const message = "Hello! I'm interested in learning more about Noore Resalat Model Madrasah. Could you please provide me with more information?"
//         const encodedMessage = encodeURIComponent(message)
//         const whatsappUrl = `https://wa.me/${whatsappNumber}?text=${encodedMessage}`
//         window.open(whatsappUrl, '_blank', 'noopener,noreferrer')
//         break
        
//       case 'call':
//         window.open(`tel:${whatsappNumber.replace('+', '')}`, '_self')
//         break
        
//       case 'email':
//         const email = contactData?.contactMethods?.email?.[0] || 'info@al-abrar.com'
//         window.open(`mailto:${email}`, '_self')
//         break
        
//       case 'chatbot':
//         setShowChatbotPopup(true)
//         break
//     }
    
//     setIsOpen(false)
//   }

//   const contactOptions = [
//     {
//       id: 'chatbot' as ContactOption,
//       icon: Bot,
//       label: 'AI Assistant',
//       color: 'bg-purple-600 hover:bg-purple-700',
//       iconBg: 'bg-purple-700 group-hover:bg-purple-800',
//       delay: 'delay-0'
//     },
//     {
//       id: 'whatsapp' as ContactOption,
//       icon: MessageCircle,
//       label: 'WhatsApp',
//       color: 'bg-green-600 hover:bg-green-700',
//       iconBg: 'bg-green-700 group-hover:bg-green-800',
//       delay: 'delay-75'
//     },
 
//   ]

//   if (isLoading) {
//     return (
//       <div className="fixed bottom-6 right-6 z-[999999]">
//         <div className="animate-pulse">
//           <div className="w-14 h-14 bg-gradient-to-br from-green-500 to-green-600 rounded-full flex items-center justify-center shadow-2xl border-2 border-white">
//             <MessageCircle className="w-6 h-6 text-white" />
//           </div>
//         </div>
//       </div>
//     )
//   }

//   return (
//     <>
//       {/* AI Chatbot Not Activated Popup */}
//       {showChatbotPopup && (
//         <div className="fixed inset-0 z-[999999] bg-black/50 flex items-center justify-center p-4 animate-in fade-in-0 duration-200">
//           <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md animate-in zoom-in-95 duration-300">
//             {/* Header */}
//             <div className="flex items-center gap-3 p-6 border-b">
//               <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-full flex items-center justify-center">
//                 <Bot className="w-5 h-5 text-white" />
//               </div>
//               <div className="flex-1">
//                 <h3 className="text-lg font-semibold text-gray-800">AI Assistant</h3>
//                 <p className="text-sm text-gray-500">Coming Soon</p>
//               </div>
//               <button 
//                 onClick={() => setShowChatbotPopup(false)}
//                 className="p-2 hover:bg-gray-100 rounded-full transition-colors"
//               >
//                 <X className="w-5 h-5 text-gray-600" />
//               </button>
//             </div>

//             {/* Content */}
//             <div className="p-6 max-h-full overflow-y-auto">
//               <div className="text-center">
//                 <div className="w-20 h-20 bg-gradient-to-br from-purple-100 to-purple-200 rounded-full flex items-center justify-center mx-auto mb-4">
//                   <Bot className="w-8 h-8 text-purple-600" />
//                 </div>
//                 <h4 className="text-xl font-semibold text-gray-800 mb-2">
//                   AI Assistant Not Activated Yet
//                 </h4>
//                 <p className="text-gray-600 mb-6">
//                   Our AI chatbot is currently under development and will be available soon. 
//                   In the meantime, please use our other contact methods for assistance.
//                 </p>
                
//                 <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
//                   <div className="flex items-center gap-2 text-yellow-800">
//                     <div className="w-2 h-2 bg-yellow-500 rounded-full animate-pulse"></div>
//                     <span className="text-sm font-medium">Estimated Launch: Coming Soon</span>
//                   </div>
//                 </div>
//               </div>

//               {/* Alternative Contact Options */}
//               <div className="space-y-3">
//                 <p className="text-sm text-gray-500 text-center mb-3">Get help through:</p>
                
//                 <button
//                   onClick={() => {
//                     setShowChatbotPopup(false)
//                     handleContactClick('whatsapp')
//                   }}
//                   className="w-full flex items-center gap-3 p-3 bg-green-50 hover:bg-green-100 rounded-lg transition-colors group"
//                 >
//                   <div className="w-8 h-8 bg-green-600 rounded-full flex items-center justify-center">
//                     <MessageCircle className="w-4 h-4 text-white" />
//                   </div>
//                   <div className="text-left">
//                     <p className="font-medium text-gray-800">WhatsApp Support</p>
//                     <p className="text-xs text-gray-600">Instant messaging with our team</p>
//                   </div>
//                 </button>

              

//               </div>
//             </div>

//             {/* Footer */}
//             <div className="bg-gray-50 rounded-b-2xl px-6 py-4 border-t">
//               <p className="text-xs text-gray-500 text-center">
//                 Our team is working hard to bring you the best AI experience
//               </p>
//             </div>
//           </div>
//         </div>
//       )}

//       {/* Main Floating Widget */}
//       <div className="fixed bottom-6 right-6 z-[999999]">
//         {/* Welcome Notification */}
//         {showNotification && !isOpen && !showChatbotPopup && (
//           <div className="absolute bottom-20 right-0 bg-gradient-to-r from-green-600 to-green-700 text-white p-4 rounded-lg shadow-2xl w-80 animate-in fade-in-0 slide-in-from-right-4 mb-4">
//             <div className="flex items-start gap-3">
//               <div className="flex-1">
//                 <h4 className="font-semibold text-sm mb-1">Need Help?</h4>
//                 <p className="text-xs text-green-100 mb-2">
//                   Chat with our AI assistant, call, or message us for instant help with admissions and programs.
//                 </p>
//                 <p className="text-xs text-green-200">
//                   Office Hours: {contactData?.officeHours?.regular || '9:15 AM - 2:30 PM'}
//                 </p>
//               </div>
//               <button 
//                 onClick={() => setShowNotification(false)}
//                 className="text-green-200 hover:text-white transition-colors flex-shrink-0"
//               >
//                 <X className="w-4 h-4" />
//               </button>
//             </div>
//             <div className="absolute -bottom-2 right-6 w-4 h-4 bg-green-600 rotate-45"></div>
//           </div>
//         )}

//         {/* Expanded Contact Options */}
//         {isOpen && (
//           <div className="absolute bottom-16 right-0 mb-4 space-y-2 animate-in fade-in-0 zoom-in-95 duration-200">
//             {contactOptions.map((option) => (
//               <button
//                 key={option.id}
//                 onClick={() => handleContactClick(option.id)}
//                 className={`
//                   flex items-center gap-3 text-white px-4 py-3 rounded-full shadow-2xl 
//                   transition-all duration-200 group animate-in slide-in-from-right-4 
//                   hover:scale-105 ${option.color} ${option.delay}
//                 `}
//               >
//                 <div className={`p-1 rounded-full transition-colors ${option.iconBg}`}>
//                   <option.icon className="w-4 h-4" />
//                 </div>
//                 <span className="text-sm font-medium whitespace-nowrap">{option.label}</span>
//               </button>
//             ))}
//           </div>
//         )}

//         {/* Main Floating Button */}
//         <button
//           onClick={() => setIsOpen(!isOpen)}
//           className={`
//             relative w-14 h-14 rounded-full shadow-2xl transition-all duration-300 
//             flex items-center justify-center border-2 border-white
//             ${
//               isOpen 
//                 ? 'bg-gradient-to-br from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 rotate-45 scale-110' 
//                 : 'bg-gradient-to-br from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 hover:scale-110'
//             }
//           `}
//         >
//           {isOpen ? (
//             <X className="w-6 h-6 text-white" />
//           ) : (
//             <MessageCircle className="w-6 h-6 text-white" />
//           )}
          
//           {/* Ping Animation */}
//           {!isOpen && !showChatbotPopup && (
//             <div className="absolute inset-0 rounded-full bg-green-400 animate-ping opacity-75 -z-10"></div>
//           )}

//           {/* Online Status Dot */}
//           <div className="absolute -top-1 -right-1 w-4 h-4 bg-green-400 border-2 border-white rounded-full animate-pulse"></div>
//         </button>

//         {/* Tooltip */}
//         {!isOpen && !showChatbotPopup && (
//           <div className="absolute bottom-20 right-0 bg-gray-900 text-white text-xs px-3 py-2 rounded-lg shadow-lg whitespace-nowrap animate-in fade-in-0 zoom-in-95 mb-2">
//             Contact Support
//             <div className="absolute -bottom-1 right-6 w-2 h-2 bg-gray-900 rotate-45"></div>
//           </div>
//         )}
//       </div>
//     </>
//   )
// }