/* eslint-disable prefer-const */
/* eslint-disable @typescript-eslint/no-explicit-any */
'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 FloatingContactWidget() {
  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)

  // Fetch contact info
  useEffect(() => {
    const fetchContactInfo = async () => {
      try {
        const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/contact-info`)
        const data = await res.json()
        if (data.success && data.data) {
          const info: ContactInfo = data.data
          setContactData(info)

          let number = info.contactMethods?.socialMedia?.whatsapp || info.contactMethods?.phone?.[0] || '+8801873515482'
          setWhatsappNumber(formatNumber(number))
        }
      } catch (err) {
        console.error(err)
      } finally {
        setIsLoading(false)
      }
    }
    fetchContactInfo()
  }, [])

  const formatNumber = (number: string) => {
    let n = number.replace(/[^\d+]/g, '')
    if (!n.startsWith('+88')) n = n.startsWith('0') ? `+88${n.slice(1)}` : `+88${n}`
    return n
  }

  const handleClick = (option: ContactOption) => {
    switch (option) {
      case 'whatsapp':
        const msg = encodeURIComponent("Hello! I need more info about your programs.")
        window.open(`https://wa.me/${whatsappNumber}?text=${msg}`, '_blank')
        break
      case 'call':
        window.open(`tel:${whatsappNumber.replace('+', '')}`, '_self')
        break
      case 'email':
        const email = contactData?.contactMethods?.email?.[0] || 'info@school.com'
        window.open(`mailto:${email}`, '_self')
        break
      case 'chatbot':
        setShowChatbot(true)
        break
    }
    setIsOpen(false)
  }

  const options: { id: ContactOption; icon: any; label: string; color: string; delay: string }[] = [
    { id: 'chatbot', icon: Bot, label: 'AI Assistant', color: 'bg-purple-600 hover:bg-purple-700', delay: 'delay-0' },
    { id: 'whatsapp', icon: MessageCircle, label: 'WhatsApp', color: 'bg-green-500 hover:bg-green-600', delay: 'delay-75' },
  ]

  if (isLoading) {
    return (
      <div className="fixed bottom-6 right-6 z-9999">
        <div className="animate-pulse">
          <div className="w-16 h-16 rounded-full bg-linear-to-br from-green-400 to-green-600 flex items-center justify-center shadow-2xl border-2 border-white">
            <MessageCircle className="w-6 h-6 text-white" />
          </div>
        </div>
      </div>
    )
  }

  return (
    <>
      {/* Chatbot Modal */}
      {showChatbot && (
        <div className="fixed inset-0 z-9999 bg-black/50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl h-[80vh] animate-in zoom-in-95 duration-300 flex flex-col">
            <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">
                <X className="w-5 h-5 text-gray-600" />
              </button>
            </div>
            <div className="flex-1 overflow-y-auto">
              <AiChatbot onClose={() => setShowChatbot(false)} />
            </div>
          </div>
        </div>
      )}

      {/* Floating Widget */}
      <div className="fixed bottom-6 right-6 z-9999 flex flex-col items-end gap-2">
        {/* Notification Bubble */}
        {showNotification && !isOpen && !showChatbot && (
          <div className="bg-linear-to-r from-green-500 to-green-600 text-white p-3 rounded-xl shadow-xl w-80 animate-in slide-in-from-right-4 relative">
            <div className="flex items-start gap-2">
              <div className="flex-1">
                <h4 className="font-semibold text-sm mb-1">Need Assistance?</h4>
                <p className="text-xs text-green-100 mb-1">
                  Chat, call, or message us for quick guidance.
                </p>
                <p className="text-[10px] 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">
                <X className="w-4 h-4" />
              </button>
            </div>
            <div className="absolute -bottom-2 right-6 w-4 h-4 bg-green-500 rotate-45"></div>
          </div>
        )}

        {/* Expanded Contact Buttons */}
        {isOpen && (
          <div className="flex flex-col items-end gap-2 animate-in fade-in-0 zoom-in-95">
            {options.map((opt) => (
              <button
                key={opt.id}
                onClick={() => handleClick(opt.id)}
                className={`flex items-center gap-3 px-4 py-3 rounded-full shadow-xl text-white transition-transform hover:scale-105 ${opt.color} ${opt.delay}`}
              >
                <div className="p-1 rounded-full bg-white/20 flex items-center justify-center">
                  <opt.icon className="w-4 h-4" />
                </div>
                <span className="text-sm font-medium">{opt.label}</span>
              </button>
            ))}
          </div>
        )}

        {/* Main Floating Button */}
        <button
          onClick={() => setIsOpen(!isOpen)}
          className={`w-16 h-16 rounded-full shadow-2xl border-2 border-white flex items-center justify-center transition-transform ${
            isOpen
              ? 'bg-red-500 rotate-45 scale-110 hover:scale-115'
              : 'bg-linear-to-br from-green-500 to-green-600 hover:scale-110'
          } relative`}
        >
          {isOpen ? <X className="w-6 h-6 text-white" /> : <MessageCircle className="w-6 h-6 text-white" />}
          {!isOpen && !showChatbot && (
            <div className="absolute inset-0 rounded-full bg-green-400 animate-ping opacity-50 -z-10"></div>
          )}
          <div className="absolute -top-1 -right-1 w-4 h-4 bg-green-400 border-2 border-white rounded-full animate-pulse"></div>
        </button>
      </div>
    </>
  )
}
