'use client'

import { MessageCircle } from 'lucide-react'
import { useState, useEffect } from 'react'

export default function WhatsAppFloat() {
  const [isVisible, setIsVisible] = useState(false)
  const [settings, setSettings] = useState<any>(null)

  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const response = await fetch('/api/settings')
        if (response.ok) {
          const data = await response.json()
          setSettings(data.settings || {})
        } else {
          // Set default settings if API fails
          setSettings({ contactWhatsApp: '+62 812-3456-7890' })
        }
      } catch (error) {
        console.error('Error fetching settings:', error)
        // Set default settings on error
        setSettings({ contactWhatsApp: '+62 812-3456-7890' })
      }
    }

    fetchSettings()
  }, [])

  useEffect(() => {
    const timer = setTimeout(() => setIsVisible(true), 1000)
    return () => clearTimeout(timer)
  }, [])

  // Always show if visible, use default WhatsApp number if not set
  if (!isVisible) {
    return null
  }

  const whatsappNumber = settings?.contactWhatsApp || '+62 812-3456-7890'
  
  const formatWhatsAppNumber = (phone: string) => {
    // Remove all non-digit characters and ensure it starts with country code
    const cleaned = phone.replace(/\D/g, '')
    if (cleaned.startsWith('0')) {
      return '62' + cleaned.substring(1)
    }
    return cleaned
  }

  const formattedNumber = formatWhatsAppNumber(whatsappNumber)
  const whatsappMessage = encodeURIComponent('Halo, saya ingin bertanya tentang layanan Polres Wonosobo.')

  return (
    <div className="fixed bottom-6 right-6 z-50 flex flex-col items-end gap-2 group">
      <div className="bg-white px-4 py-2 rounded-lg shadow-lg opacity-0 transition-all duration-300 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0">
        <p className="text-sm font-medium text-gray-700">Hubungi Kami</p>
      </div>
      
      <a
        href={`https://wa.me/${formattedNumber}?text=${whatsappMessage}`}
        target="_blank"
        rel="noopener noreferrer"
        className="group relative flex items-center justify-center w-14 h-14 bg-green-500 hover:bg-green-600 text-white rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-110"
        aria-label="Hubungi kami via WhatsApp"
      >
        <MessageCircle className="w-6 h-6" />
        
        {/* Pulse animation */}
        <span className="absolute inset-0 rounded-full bg-green-400 animate-ping opacity-75"></span>
      </a>
    </div>
  )
}