import React, { useState, useEffect, useRef } from 'react';
import { usePage } from '@inertiajs/react';

export default function WhatsAppButton() {
    const { siteinfo } = usePage().props;
    const [showMenu, setShowMenu] = useState(false);
    const containerRef = useRef(null);
    
    // Helper function to clean WhatsApp number
    const cleanWhatsAppNumber = (number) => {
        if (!number) return null;
        // Remove + and spaces, keep only digits
        return number.replace(/[\s+]/g, '');
    };
    
    // Get WhatsApp numbers from database
    const whatsappMarketingRaw = siteinfo?.whatsapp_marketing || '';
    const whatsappReceptionRaw = siteinfo?.whatsapp_reception || '';
    
    // Use fallbacks only if fields are empty
    const whatsappMarketing = cleanWhatsAppNumber(whatsappMarketingRaw || '25722405177');
    const whatsappReception = cleanWhatsAppNumber(whatsappReceptionRaw || '25762944691');
    
    const marketingUrl = `https://wa.me/${whatsappMarketing}`;
    const receptionUrl = `https://wa.me/${whatsappReception}`;

    // Close menu when clicking outside (with a small delay to allow menu clicks)
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (containerRef.current && !containerRef.current.contains(event.target)) {
                // Check if the click is not on the menu items
                const isMenuClick = event.target.closest('.whatsapp-menu');
                const isButtonClick = event.target.closest('.whatsapp-button-main');
                
                if (!isMenuClick && !isButtonClick) {
                    setShowMenu(false);
                }
            }
        };

        if (showMenu) {
            // Use a small timeout to allow menu item clicks to register first
            const timeoutId = setTimeout(() => {
                document.addEventListener('mousedown', handleClickOutside);
                document.addEventListener('touchstart', handleClickOutside);
            }, 100);
            
            return () => {
                clearTimeout(timeoutId);
                document.removeEventListener('mousedown', handleClickOutside);
                document.removeEventListener('touchstart', handleClickOutside);
            };
        }
    }, [showMenu]);

    // Always show menu version - allows users to choose between Marketing and Reception
    // This provides better UX even if numbers happen to be the same

    // Show single button with expandable menu
    return (
        <div 
            ref={containerRef}
            style={{
                position: 'fixed',
                bottom: '20px',
                right: '20px',
                zIndex: 9999,
            }}
        >
            {/* Main WhatsApp Button */}
            <button
                onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    setShowMenu(!showMenu);
                }}
                className="whatsapp-button-main"
                aria-label="Contact us on WhatsApp"
                aria-expanded={showMenu}
                style={{
                    width: '56px',
                    height: '56px',
                    background: showMenu ? '#20BA5A' : '#25D366',
                    borderRadius: '50%',
                    border: 'none',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    boxShadow: showMenu ? '0 6px 16px rgba(37, 211, 102, 0.6)' : '0 4px 12px rgba(37, 211, 102, 0.4)',
                    cursor: 'pointer',
                    color: '#fff',
                    transition: 'transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease',
                    position: 'relative',
                    zIndex: 10001,
                    transform: showMenu ? 'scale(1.1)' : 'scale(1)',
                }}
                onMouseEnter={(e) => {
                    if (!showMenu) {
                        e.currentTarget.style.transform = 'scale(1.1)';
                        e.currentTarget.style.boxShadow = '0 6px 16px rgba(37, 211, 102, 0.6)';
                        e.currentTarget.style.backgroundColor = '#20BA5A';
                    }
                }}
                onMouseLeave={(e) => {
                    if (!showMenu) {
                        e.currentTarget.style.transform = 'scale(1)';
                        e.currentTarget.style.boxShadow = '0 4px 12px rgba(37, 211, 102, 0.4)';
                        e.currentTarget.style.backgroundColor = '#25D366';
                    }
                }}
            >
                <span className="fa fa-whatsapp" style={{ fontSize: '28px', color: '#fff' }}></span>
                {showMenu && (
                    <span 
                        style={{
                            position: 'absolute',
                            fontSize: '12px',
                            fontWeight: 'bold',
                            background: '#fff',
                            color: '#25D366',
                            padding: '2px 6px',
                            borderRadius: '10px',
                            bottom: '-8px',
                            left: '50%',
                            transform: 'translateX(-50%)',
                            whiteSpace: 'nowrap',
                            boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
                        }}
                    >
                        Choose
                    </span>
                )}
            </button>

            {/* Expandable Menu */}
            {showMenu && (
            <div
                className="whatsapp-menu"
                onClick={(e) => e.stopPropagation()}
                style={{
                    position: 'absolute',
                    bottom: '70px',
                    right: '0',
                    background: '#fff',
                    borderRadius: '12px',
                    boxShadow: '0 8px 24px rgba(0,0,0,0.15)',
                    padding: '8px',
                    minWidth: '180px',
                    zIndex: 10000,
                    animation: 'fadeInUp 0.2s ease-out',
                }}
            >
                {/* Marketing Option */}
                <a
                    href={marketingUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    onClick={() => setShowMenu(false)}
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        padding: '12px 16px',
                        borderRadius: '8px',
                        textDecoration: 'none',
                        color: '#333',
                        transition: 'background-color 0.2s ease',
                        marginBottom: '4px',
                        cursor: 'pointer',
                    }}
                    onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = '#f5f5f5';
                    }}
                    onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'transparent';
                    }}
                >
                    <div
                        style={{
                            width: '40px',
                            height: '40px',
                            borderRadius: '50%',
                            background: '#25D366',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            marginRight: '12px',
                            flexShrink: 0,
                        }}
                    >
                        <span className="fa fa-whatsapp" style={{ fontSize: '20px', color: '#fff' }}></span>
                    </div>
                    <div>
                        <div style={{ fontWeight: '600', fontSize: '14px', color: '#333', marginBottom: '2px' }}>
                            Marketing
                        </div>
                        <div style={{ fontSize: '12px', color: '#666' }}>
                            Sales & Marketing
                        </div>
                    </div>
                </a>

                {/* Divider */}
                <div style={{ height: '1px', background: '#e0e0e0', margin: '4px 0' }}></div>

                {/* Reception Option */}
                <a
                    href={receptionUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    onClick={() => setShowMenu(false)}
                    style={{
                        display: 'flex',
                        alignItems: 'center',
                        padding: '12px 16px',
                        borderRadius: '8px',
                        textDecoration: 'none',
                        color: '#333',
                        transition: 'background-color 0.2s ease',
                        cursor: 'pointer',
                    }}
                    onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = '#f5f5f5';
                    }}
                    onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'transparent';
                    }}
                >
                    <div
                        style={{
                            width: '40px',
                            height: '40px',
                            borderRadius: '50%',
                            background: '#128C7E',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            marginRight: '12px',
                            flexShrink: 0,
                        }}
                    >
                        <span className="fa fa-whatsapp" style={{ fontSize: '20px', color: '#fff' }}></span>
                    </div>
                    <div>
                        <div style={{ fontWeight: '600', fontSize: '14px', color: '#333', marginBottom: '2px' }}>
                            Reception
                        </div>
                        <div style={{ fontSize: '12px', color: '#666' }}>
                            Front Desk
                        </div>
                    </div>
                </a>
            </div>
            )}

            {/* Mobile: Show menu on click */}
            <style>{`
                @keyframes fadeInUp {
                    from {
                        opacity: 0;
                        transform: translateY(10px);
                    }
                    to {
                        opacity: 1;
                        transform: translateY(0);
                    }
                }
                @media (max-width: 768px) {
                    .whatsapp-button-main {
                        width: 56px !important;
                        height: 56px !important;
                    }
                    .whatsapp-menu {
                        min-width: 200px !important;
                        right: 0 !important;
                    }
                }
            `}</style>
        </div>
    );
}

