'use client';

import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { 
  X, 
  MapPin, 
  ChevronRight
} from 'lucide-react';

interface WhatsAppFloatProps {
  phoneNumber?: string;
  message?: string;
}

interface ContactNumber {
  city: string;
  phone: string;
  whatsapp: string;
  whatsappFront: string;
}

const WhatsAppFloat: React.FC<WhatsAppFloatProps> = ({ 
  phoneNumber = "923106225411",
  message = "Hello! I'm interested in your services." 
}) => {
  const [showWhatsappNumbers, setShowWhatsappNumbers] = useState(false);
  const [showCallNumbers, setShowCallNumbers] = useState(false);
  const [isVisible, setIsVisible] = useState(false);
  const [isHovered, setIsHovered] = useState(false);
  const [popupPosition, setPopupPosition] = useState({ top: 0, right: 0 });
  
  const whatsappBtnRef = useRef<HTMLDivElement>(null);
  const callBtnRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setIsVisible(true);
  }, []);

  // Calculate popup position based on button position
  const calculatePosition = (ref: React.RefObject<HTMLDivElement | null>) => {
    if (ref.current) {
      const rect = ref.current.getBoundingClientRect();
      setPopupPosition({
        top: rect.top + rect.height / 2, // Center vertically with button
        right: window.innerWidth - rect.left + 16 // Position to the left of button
      });
    }
  };

  const contactNumbers: ContactNumber[] = [
    { city: 'Lahore', phone: '+92 310 3162004', whatsapp: '923106225407', whatsappFront: '+92 310 6225407' },
    { city: 'Islamabad', phone: '+92 317 0174573', whatsapp: '923106225416', whatsappFront: '+92 310 6225416' },
    { city: 'Karachi', phone: '+92 310 6225408', whatsapp: '923170174580', whatsappFront: '+92 317 0174580' },
    { city: 'Faisalabad', phone: '+92 310 6225412', whatsapp: '923170174585', whatsappFront: '+92 317 0174585' }
  ];

  const handleCallClick = (phoneNumber: string) => {
    const cleanNumber = phoneNumber.replace(/\s+/g, '').replace('+', '');
    window.location.href = `tel:${cleanNumber}`;
    setShowCallNumbers(false);
  };

  const getWhatsAppUrl = (whatsappNumber: string, customMessage?: string) => {
    return `https://wa.me/${whatsappNumber}?text=${encodeURIComponent(customMessage || message)}`;
  };

  const toggleWhatsappNumbers = () => {
    if (!showWhatsappNumbers) {
      calculatePosition(whatsappBtnRef);
    }
    setShowWhatsappNumbers(!showWhatsappNumbers);
    setShowCallNumbers(false);
  };

  const toggleCallNumbers = () => {
    if (!showCallNumbers) {
      calculatePosition(callBtnRef);
    }
    setShowCallNumbers(!showCallNumbers);
    setShowWhatsappNumbers(false);
  };

  const handleClosePopups = () => {
    setShowWhatsappNumbers(false);
    setShowCallNumbers(false);
  };

  if (!isVisible) return null;

  return (
    <>
      {/* Overlay for closing popups when clicking outside */}
      {(showWhatsappNumbers || showCallNumbers) && (
        <div 
          className="fixed inset-0 bg-black/20 backdrop-blur-sm z-40"
          onClick={handleClosePopups}
        />
      )}

      {/* Main Container - CENTER OF SCREEN ON RIGHT SIDE FOR ALL DEVICES */}
      <div className="fixed right-6 top-1/2 -translate-y-1/2 z-50 flex flex-col items-center gap-4 md:gap-6">
        
        {/* WhatsApp Button */}
        <div 
          ref={whatsappBtnRef}
          className="relative"
          onMouseEnter={() => setIsHovered(true)}
          onMouseLeave={() => setIsHovered(false)}
        >
          {/* Animated Pulse Effect */}
          <div className="absolute inset-0 bg-linear-to-r from-green-500 to-emerald-600 rounded-full animate-ping opacity-20"></div>
          
          {/* WhatsApp Button */}
          <button 
            onClick={toggleWhatsappNumbers}
            className={`relative flex items-center justify-center bg-linear-to-r from-green-500 to-emerald-600 rounded-full p-3 md:p-4 shadow-2xl transition-all duration-300 ${
              showWhatsappNumbers ? 'scale-110 md:rotate-12' : 'hover:scale-110 hover:md:rotate-12'
            } group`}
            aria-label="Contact us on WhatsApp"
          >
            {/* Icon Container with Glow */}
            <div className="relative w-5 h-5">
              <Image
                src="/assets/whatsapp.svg"
                alt="WhatsApp"
                fill
                className="object-contain"
              />
            </div>
            
            {/* Hover Text - Desktop only */}
            <div className={`hidden md:block absolute right-full mr-4 px-3 py-1.5 bg-gray-900 text-white text-xs font-medium rounded-lg whitespace-nowrap transition-all duration-300 ${
              isHovered ? 'opacity-100 translate-x-0' : 'opacity-0 translate-x-4 pointer-events-none'
            }`}>
              WhatsApp Support
              <div className="absolute top-1/2 right-0 translate-x-1/2 -translate-y-1/2 w-2 h-2 bg-gray-900 rotate-45" />
            </div>
          </button>
        </div>

        {/* Call Button */}
        <div 
          ref={callBtnRef}
          className="relative"
          onMouseEnter={() => setIsHovered(true)}
          onMouseLeave={() => setIsHovered(false)}
        >
          {/* Animated Pulse Effect */}
          <div className="absolute inset-0 bg-linear-to-r from-blue-500 to-indigo-600 rounded-full animate-ping opacity-20"></div>
          
          <button
            onClick={toggleCallNumbers}
            className={`relative flex items-center justify-center bg-linear-to-r from-blue-500 to-indigo-600 rounded-full p-3 md:p-4 shadow-2xl transition-all duration-300 ${
              showCallNumbers ? 'scale-110 md:-rotate-12' : 'hover:scale-110 hover:md:-rotate-12'
            } group`}
            aria-label="Call us"
          >
            {/* Icon Container with Glow */}
            <div className="relative w-5 h-5">
              <svg 
                xmlns="http://www.w3.org/2000/svg" 
                viewBox="0 0 24 24" 
                fill="white"
                className="w-5 h-5"
              >
                <path fillRule="evenodd" d="M1.5 4.5a3 3 0 013-3h1.372c.86 0 1.61.586 1.819 1.42l1.105 4.423a1.875 1.875 0 01-.694 1.955l-1.293.97c-.135.101-.164.249-.126.352a11.285 11.285 0 006.697 6.697c.103.038.25.009.352-.126l.97-1.293a1.875 1.875 0 011.955-.694l4.423 1.105c.834.209 1.42.959 1.42 1.82V19.5a3 3 0 01-3 3h-2.25C8.552 22.5 1.5 15.448 1.5 6.75V4.5z" clipRule="evenodd" />
              </svg>
            </div>
            
            {/* Hover Text - Desktop only */}
            <div className={`hidden md:block absolute right-full mr-4 px-3 py-1.5 bg-gray-900 text-white text-xs font-medium rounded-lg whitespace-nowrap transition-all duration-300 ${
              isHovered ? 'opacity-100 translate-x-0' : 'opacity-0 translate-x-4 pointer-events-none'
            }`}>
              Call Support
              <div className="absolute top-1/2 right-0 translate-x-1/2 -translate-y-1/2 w-2 h-2 bg-gray-900 rotate-45" />
            </div>
          </button>
        </div>
      </div>

      {/* MOBILE POPUPS - Separate positioning for mobile */}
      {/* WhatsApp Popup - Mobile */}
      {showWhatsappNumbers && (
        <div className="md:hidden fixed inset-x-4 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-2xl shadow-2xl p-4 border border-gray-100 animate-in zoom-in duration-300 z-50 max-h-[80vh] overflow-y-auto w-[calc(100%-2rem)] max-w-md">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <span className="text-xl">💬</span>
              <span className="font-semibold text-gray-900">WhatsApp Support</span>
            </div>
            <button
              onClick={handleClosePopups}
              className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
          <div className="space-y-3">
            {contactNumbers.map((item, index) => (
              <Link
                key={index}
                href={getWhatsAppUrl(item.whatsapp)}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center justify-between p-3 rounded-xl bg-gray-50 hover:bg-emerald-50 transition-colors border border-gray-100"
                onClick={() => setShowWhatsappNumbers(false)}
              >
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-linear-to-r from-green-500 to-emerald-600 flex items-center justify-center">
                    <div className="relative w-4 h-4">
                      <Image
                        src="/assets/whatsapp.svg"
                        alt="WhatsApp"
                        fill
                        className="object-contain"
                      />
                    </div>
                  </div>
                  <div>
                    <div className="flex items-center gap-1">
                      <MapPin className="w-3.5 h-3.5 text-emerald-600" />
                      <span className="font-medium text-gray-900">{item.city}</span>
                    </div>
                    <div className="text-sm text-emerald-600 font-medium mt-1">
                      {item.whatsappFront}
                    </div>
                  </div>
                </div>
                <ChevronRight className="w-4 h-4 text-emerald-600" />
              </Link>
            ))}
          </div>
        </div>
      )}

      {/* Call Popup - Mobile */}
      {showCallNumbers && (
        <div className="md:hidden fixed inset-x-4 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-white rounded-2xl shadow-2xl p-4 border border-gray-100 animate-in zoom-in duration-300 z-50 max-h-[80vh] overflow-y-auto w-[calc(100%-2rem)] max-w-md">
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-2">
              <span className="text-xl">📞</span>
              <span className="font-semibold text-gray-900">Call Support</span>
            </div>
            <button
              onClick={handleClosePopups}
              className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
          <div className="space-y-3">
            {contactNumbers.map((item, index) => (
              <button
                key={index}
                onClick={() => handleCallClick(item.phone)}
                className="w-full flex items-center justify-between p-3 rounded-xl bg-gray-50 hover:bg-blue-50 transition-colors text-left border border-gray-100"
              >
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-linear-to-r from-blue-500 to-indigo-600 flex items-center justify-center">
                    <svg 
                      xmlns="http://www.w3.org/2000/svg" 
                      viewBox="0 0 24 24" 
                      fill="white"
                      className="w-4 h-4"
                    >
                      <path fillRule="evenodd" d="M1.5 4.5a3 3 0 013-3h1.372c.86 0 1.61.586 1.819 1.42l1.105 4.423a1.875 1.875 0 01-.694 1.955l-1.293.97c-.135.101-.164.249-.126.352a11.285 11.285 0 006.697 6.697c.103.038.25.009.352-.126l.97-1.293a1.875 1.875 0 011.955-.694l4.423 1.105c.834.209 1.42.959 1.42 1.82V19.5a3 3 0 01-3 3h-2.25C8.552 22.5 1.5 15.448 1.5 6.75V4.5z" clipRule="evenodd" />
                    </svg>
                  </div>
                  <div>
                    <div className="flex items-center gap-1">
                      <MapPin className="w-3.5 h-3.5 text-blue-600" />
                      <span className="font-medium text-gray-900">{item.city}</span>
                    </div>
                    <div className="text-sm text-blue-600 font-medium mt-1">
                      {item.phone}
                    </div>
                  </div>
                </div>
                <div className="w-8 h-8 rounded-full bg-blue-50 flex items-center justify-center">
                  <svg 
                    xmlns="http://www.w3.org/2000/svg" 
                    viewBox="0 0 24 24" 
                    fill="#3b82f6"
                    className="w-4 h-4"
                  >
                    <path fillRule="evenodd" d="M1.5 4.5a3 3 0 013-3h1.372c.86 0 1.61.586 1.819 1.42l1.105 4.423a1.875 1.875 0 01-.694 1.955l-1.293.97c-.135.101-.164.249-.126.352a11.285 11.285 0 006.697 6.697c.103.038.25.009.352-.126l.97-1.293a1.875 1.875 0 011.955-.694l4.423 1.105c.834.209 1.42.959 1.42 1.82V19.5a3 3 0 01-3 3h-2.25C8.552 22.5 1.5 15.448 1.5 6.75V4.5z" clipRule="evenodd" />
                  </svg>
                </div>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* DESKTOP POPUPS - Fixed positioning based on button location */}
      {/* WhatsApp Popup - Desktop */}
      {showWhatsappNumbers && (
        <div 
          className="hidden md:block fixed bg-white rounded-2xl shadow-2xl p-6 w-80 border border-gray-100 animate-in slide-in-from-right-5 duration-300 z-50"
          style={{
            top: `${popupPosition.top}px`,
            right: `${popupPosition.right}px`,
            transform: 'translateY(-50%)'
          }}
        >
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-linear-to-r from-green-100 to-emerald-100 flex items-center justify-center">
                <span className="text-2xl">💬</span>
              </div>
              <div>
                <h3 className="font-bold text-gray-900">WhatsApp Support</h3>
                <p className="text-sm text-gray-500">Select your city to chat</p>
              </div>
            </div>
            <button
              onClick={handleClosePopups}
              className="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-500 hover:text-gray-700 transition-colors"
            >
              <X className="w-4 h-4" />
            </button>
          </div>

          <div className="space-y-4">
            {contactNumbers.map((item, index) => (
              <Link
                key={index}
                href={getWhatsAppUrl(item.whatsapp)}
                target="_blank"
                rel="noopener noreferrer"
                className="group flex items-center gap-4 p-4 rounded-xl hover:bg-linear-to-r hover:from-green-50 hover:to-emerald-50 border border-gray-100 hover:border-emerald-200 transition-all duration-300"
                onClick={() => setShowWhatsappNumbers(false)}
              >
                <div className="w-10 h-10 rounded-full bg-linear-to-r from-green-500 to-emerald-600 flex items-center justify-center shadow-sm">
                  <div className="relative w-5 h-5">
                    <Image
                      src="/assets/whatsapp.svg"
                      alt="WhatsApp"
                      fill
                      className="object-contain"
                    />
                  </div>
                </div>
                
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <MapPin className="w-3.5 h-3.5 text-emerald-600" />
                    <span className="font-semibold text-gray-900">{item.city}</span>
                  </div>
                  <div className="text-sm text-emerald-600 font-medium mt-1">
                    {item.whatsappFront}
                  </div>
                </div>
                
                <ChevronRight className="w-4 h-4 text-gray-400 group-hover:text-emerald-600 transition-colors" />
              </Link>
            ))}
          </div>

          <div className="mt-6 pt-5 border-t border-gray-100">
            <p className="text-xs text-gray-500 text-center">
              Typically replies within minutes
            </p>
          </div>
        </div>
      )}

      {/* Call Popup - Desktop */}
      {showCallNumbers && (
        <div 
          className="hidden md:block fixed bg-white rounded-2xl shadow-2xl p-6 w-80 border border-gray-100 animate-in slide-in-from-right-5 duration-300 z-50"
          style={{
            top: `${popupPosition.top}px`,
            right: `${popupPosition.right}px`,
            transform: 'translateY(-50%)'
          }}
        >
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-linear-to-r from-blue-100 to-indigo-100 flex items-center justify-center">
                <span className="text-2xl">📞</span>
              </div>
              <div>
                <h3 className="font-bold text-gray-900">Call Support</h3>
                <p className="text-sm text-gray-500">Available 24/7</p>
              </div>
            </div>
            <button
              onClick={handleClosePopups}
              className="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-500 hover:text-gray-700 transition-colors"
            >
              <X className="w-4 h-4" />
            </button>
          </div>

          <div className="space-y-4">
            {contactNumbers.map((item, index) => (
              <button
                key={index}
                onClick={() => handleCallClick(item.phone)}
                className="group flex items-center gap-4 p-4 rounded-xl hover:bg-linear-to-r hover:from-blue-50 hover:to-indigo-50 border border-gray-100 hover:border-blue-200 transition-all duration-300 w-full text-left"
              >
                <div className="w-10 h-10 rounded-full bg-linear-to-r from-blue-500 to-indigo-600 flex items-center justify-center shadow-sm">
                  <svg 
                    xmlns="http://www.w3.org/2000/svg" 
                    viewBox="0 0 24 24" 
                    fill="white"
                    className="w-5 h-5"
                  >
                    <path fillRule="evenodd" d="M1.5 4.5a3 3 0 013-3h1.372c.86 0 1.61.586 1.819 1.42l1.105 4.423a1.875 1.875 0 01-.694 1.955l-1.293.97c-.135.101-.164.249-.126.352a11.285 11.285 0 006.697 6.697c.103.038.25.009.352-.126l.97-1.293a1.875 1.875 0 011.955-.694l4.423 1.105c.834.209 1.42.959 1.42 1.82V19.5a3 3 0 01-3 3h-2.25C8.552 22.5 1.5 15.448 1.5 6.75V4.5z" clipRule="evenodd" />
                  </svg>
                </div>
                
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <MapPin className="w-3.5 h-3.5 text-blue-600" />
                    <span className="font-semibold text-gray-900">{item.city}</span>
                  </div>
                  <div className="text-sm text-blue-600 font-medium mt-1">
                    {item.phone}
                  </div>
                </div>
                
                <div className="w-8 h-8 rounded-full bg-blue-50 group-hover:bg-blue-100 flex items-center justify-center transition-colors">
                  <svg 
                    xmlns="http://www.w3.org/2000/svg" 
                    viewBox="0 0 24 24" 
                    fill="#3b82f6"
                    className="w-4 h-4"
                  >
                    <path fillRule="evenodd" d="M1.5 4.5a3 3 0 013-3h1.372c.86 0 1.61.586 1.819 1.42l1.105 4.423a1.875 1.875 0 01-.694 1.955l-1.293.97c-.135.101-.164.249-.126.352a11.285 11.285 0 006.697 6.697c.103.038.25.009.352-.126l.97-1.293a1.875 1.875 0 011.955-.694l4.423 1.105c.834.209 1.42.959 1.42 1.82V19.5a3 3 0 01-3 3h-2.25C8.552 22.5 1.5 15.448 1.5 6.75V4.5z" clipRule="evenodd" />
                  </svg>
                </div>
              </button>
            ))}
          </div>

          <div className="mt-6 pt-5 border-t border-gray-100">
            <div className="flex items-center justify-center gap-2 text-xs text-gray-500">
              <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />
              <span>Available now</span>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default WhatsAppFloat;