import React, { useState, useEffect } from 'react';
import { ArrowUp, X, Send } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { useData } from '../context/DataContext';

interface FloatingWhatsAppProps {
  onOpenConsult: () => void;
}

export const FloatingWhatsApp: React.FC<FloatingWhatsAppProps> = ({ onOpenConsult }) => {
  const { settings } = useData();
  const [showScrollTop, setShowScrollTop] = useState(false);
  const [showChatBubble, setShowChatBubble] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 400) {
        setShowScrollTop(true);
      } else {
        setShowScrollTop(false);
      }
    };
    window.addEventListener('scroll', handleScroll);

    // Show friendly chat bubble after 4 seconds to invite customer interaction
    const timer = setTimeout(() => {
      setShowChatBubble(true);
    }, 4000);

    return () => {
      window.removeEventListener('scroll', handleScroll);
      clearTimeout(timer);
    };
  }, []);

  const scrollToTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleWhatsAppClick = () => {
    const waNumber = (settings.whatsapp || "6281234567890").replace(/[^0-9]/g, '');
    const text = encodeURIComponent('Halo Tukang Dekorasi, saya ingin berkonsultasi mengenai layanan dekorasi...');
    window.open(`https://wa.me/${waNumber}?text=${text}`, '_blank', 'noopener,noreferrer');
  };

  return (
    <div className="fixed bottom-6 right-6 z-40 flex flex-col items-end gap-3 pointer-events-none">
      {/* Scroll to top (interactive elements need pointer-events-auto) */}
      <AnimatePresence>
        {showScrollTop && (
          <motion.button
            initial={{ opacity: 0, y: 10, scale: 0.8 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 10, scale: 0.8 }}
            onClick={scrollToTop}
            className="p-3 rounded-full bg-white text-gray-700 shadow-xl border border-gray-100 hover:bg-gray-50 hover:text-[#6B8E5A] transition-all duration-300 pointer-events-auto"
            aria-label="Kembali ke atas"
          >
            <ArrowUp className="w-5 h-5" />
          </motion.button>
        )}
      </AnimatePresence>

      {/* Floating Chat Box / Invitation Card */}
      <AnimatePresence>
        {showChatBubble && (
          <motion.div
            initial={{ opacity: 0, scale: 0.9, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.9, y: 20 }}
            className="bg-white rounded-2xl shadow-2xl border border-gray-100 p-4 max-w-[280px] md:max-w-[320px] pointer-events-auto relative mb-1"
          >
            {/* Header / Avatar */}
            <div className="flex items-start justify-between gap-3 pb-3 border-b border-gray-100">
              <div className="flex items-center gap-2.5">
                <div className="relative">
                  <div className="w-9 h-9 rounded-full bg-[#EBF4E7] flex items-center justify-center font-bold text-[#6B8E5A] text-sm">
                    TD
                  </div>
                  <span className="absolute bottom-0 right-0 w-2.5 h-2.5 bg-emerald-500 border-2 border-white rounded-full"></span>
                </div>
                <div>
                  <h4 className="text-xs font-bold text-gray-800">Tukang Dekorasi</h4>
                  <p className="text-[10px] text-gray-400">Hubungi CS Online (Aktif)</p>
                </div>
              </div>
              <button
                onClick={() => setShowChatBubble(false)}
                className="p-1 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-50 transition"
                aria-label="Tutup"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Message Body */}
            <div className="py-3">
              <p className="text-xs text-gray-600 leading-relaxed">
                Halo! Kami siap membantu mewujudkan dekorasi & landscape impian Anda. Ingin tanya-tanya dlu? Chat langsung ke WA ya! 😊
              </p>
            </div>

            {/* Quick Action Button */}
            <button
              onClick={handleWhatsAppClick}
              className="w-full py-2 px-3 bg-[#25D366] hover:bg-[#20b858] text-white rounded-xl font-medium text-xs flex items-center justify-center gap-2 shadow-sm transition-all duration-300"
            >
              <Send className="w-3.5 h-3.5" />
              <span>Mulai Chat WhatsApp</span>
            </button>
          </motion.div>
        )}
      </AnimatePresence>

      {/* WhatsApp Main Pulsing Button */}
      <div className="relative flex items-center pointer-events-auto">
        <button
          onClick={() => {
            handleWhatsAppClick();
            // Toggle bubble show/hide on click if they want
            setShowChatBubble(prev => !prev);
          }}
          className="relative p-3.5 rounded-full bg-[#25D366] hover:bg-[#20b858] text-white shadow-2xl transition-all duration-300 transform hover:scale-110 active:scale-95 flex items-center justify-center cursor-pointer group"
          aria-label="Chat WhatsApp Tukang Dekorasi"
        >
          {/* Pulsing ring background */}
          <span className="absolute inset-0 rounded-full bg-[#25D366] opacity-40 animate-ping -z-10"></span>
          
          {/* Logo SVG Image with no-referrer for privacy/security */}
          <img
            src="https://upload.wikimedia.org/wikipedia/commons/6/6b/WhatsApp.svg"
            alt="WhatsApp"
            className="w-7 h-7 filter brightness-100"
            referrerPolicy="no-referrer"
          />
        </button>
      </div>
    </div>
  );
};

