import React, { useState, useEffect } from 'react';
import { 
  X, 
  ExternalLink, 
  RotateCw, 
  Sparkles, 
  Loader2, 
  MessageSquare,
  ShieldCheck,
  CalendarCheck
} from 'lucide-react';
import { BOOKING_FORM_URL, BOOKING_FORM_EMBED_URL } from '../data/yachtData';

interface BookingModalProps {
  isOpen: boolean;
  onClose: () => void;
  bookingData?: any;
}

export const BookingModal: React.FC<BookingModalProps> = ({
  isOpen,
  onClose,
}) => {
  const [isLoading, setIsLoading] = useState(true);
  const [iframeKey, setIframeKey] = useState(0);

  // Close on Escape key
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        onClose();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, onClose]);

  // Reset loading state when opened
  useEffect(() => {
    if (isOpen) {
      setIsLoading(true);
    }
  }, [isOpen, iframeKey]);

  if (!isOpen) return null;

  const handleRefresh = () => {
    setIsLoading(true);
    setIframeKey(prev => prev + 1);
  };

  const handleOpenWhatsApp = () => {
    const text = `Hi Entourage VIP Team! 🛥️ I would like to make an enquiry about chartering the 75ft Entourage Yacht in Aberdeen, Hong Kong.`;
    window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(text)}`, '_blank', 'noopener,noreferrer');
  };

  return (
    <div 
      className="fixed inset-0 z-50 flex items-center justify-center p-2 sm:p-4 md:p-6 bg-black/85 backdrop-blur-md transition-opacity animate-in fade-in duration-200"
      onClick={onClose}
    >
      <div 
        className="relative w-full max-w-4xl h-[92vh] sm:h-[88vh] bg-[#1e2a38] border border-[#517e8a]/40 rounded-2xl sm:rounded-3xl shadow-2xl flex flex-col overflow-hidden animate-in zoom-in-95 duration-200"
        onClick={(e) => e.stopPropagation()}
      >
        
        {/* Top Header Bar */}
        <div className="flex items-center justify-between px-4 sm:px-6 py-3.5 bg-[#172230] border-b border-[#517e8a]/30 shrink-0 select-none">
          
          {/* Title & Badge */}
          <div className="flex items-center gap-2.5 sm:gap-3">
            <div className="w-8 h-8 sm:w-9 sm:h-9 rounded-xl bg-[#e17f52]/20 border border-[#e17f52]/40 flex items-center justify-center text-[#e17f52] shrink-0">
              <CalendarCheck className="w-4 h-4 sm:w-5 sm:h-5" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h3 className="text-sm sm:text-base font-bold text-white tracking-wide">
                  Charter & Viewing Enquiry
                </h3>
                <span className="hidden sm:inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-[#e17f52]/20 text-[#e17f52] border border-[#e17f52]/30 text-[10px] font-semibold uppercase">
                  <Sparkles className="w-2.5 h-2.5" />
                  Official Form
                </span>
              </div>
              <p className="text-[11px] text-slate-300 hidden sm:block">
                Entourage • 22m / 75ft Luxury Superyacht Hong Kong
              </p>
            </div>
          </div>

          {/* Action Toolbar */}
          <div className="flex items-center gap-1.5 sm:gap-2">
            {/* Refresh Button */}
            <button
              onClick={handleRefresh}
              title="Reload Form Frame"
              className="p-2 rounded-xl bg-[#1e2a38] hover:bg-[#2b3b4e] text-slate-300 hover:text-white border border-[#517e8a]/30 transition-colors cursor-pointer"
              aria-label="Reload Form"
            >
              <RotateCw className="w-4 h-4" />
            </button>

            {/* Direct External Link */}
            <a
              href={BOOKING_FORM_URL}
              target="_blank"
              rel="noopener noreferrer"
              title="Open Google Form in New Window"
              className="hidden sm:inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-[#2b3b4e] hover:bg-[#3b4e63] text-slate-200 hover:text-white border border-[#517e8a]/40 text-xs font-semibold transition-colors cursor-pointer"
            >
              <span>New Window</span>
              <ExternalLink className="w-3.5 h-3.5 text-[#e17f52]" />
            </a>

            {/* Close Button */}
            <button
              onClick={onClose}
              className="p-2 rounded-xl bg-[#2b3b4e] hover:bg-[#e17f52] text-slate-300 hover:text-white border border-[#517e8a]/30 transition-all cursor-pointer ml-1"
              aria-label="Close Enquiry Frame"
            >
              <X className="w-4 h-4 sm:w-5 sm:h-5" />
            </button>
          </div>
        </div>

        {/* Embedded Iframe Body with Loading State */}
        <div className="relative flex-1 w-full bg-white overflow-hidden">
          
          {/* Loading Spinner Indicator */}
          {isLoading && (
            <div className="absolute inset-0 z-10 flex flex-col items-center justify-center bg-[#1e2a38] text-white p-6 space-y-3">
              <Loader2 className="w-8 h-8 text-[#e17f52] animate-spin" />
              <div className="text-center space-y-1">
                <p className="text-sm font-semibold text-slate-200">Loading Enquiry Form Frame...</p>
                <p className="text-xs text-slate-400">Connecting to official Google Forms portal</p>
              </div>
            </div>
          )}

          {/* Embedded Google Form Iframe */}
          <iframe
            key={iframeKey}
            src={BOOKING_FORM_EMBED_URL}
            title="Entourage Yacht Booking Enquiry Form"
            className="w-full h-full border-0 bg-white"
            onLoad={() => setIsLoading(false)}
            loading="lazy"
          />
        </div>

        {/* Bottom Helper Bar */}
        <div className="px-4 py-2.5 bg-[#172230] border-t border-[#517e8a]/30 flex flex-col sm:flex-row items-center justify-between gap-2 text-xs text-slate-300 shrink-0">
          <div className="flex items-center gap-2 text-[11px] text-slate-400">
            <ShieldCheck className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
            <span>Encrypted submission • Responses reviewed within 24 hours</span>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={handleOpenWhatsApp}
              className="text-[#e17f52] hover:text-[#ea8e64] text-[11px] font-medium flex items-center gap-1 cursor-pointer transition-colors"
            >
              <MessageSquare className="w-3.5 h-3.5" />
              <span>Need urgent assistance? WhatsApp Concierge</span>
            </button>
            <span className="text-slate-600 hidden sm:inline">|</span>
            <a
              href={BOOKING_FORM_URL}
              target="_blank"
              rel="noopener noreferrer"
              className="text-slate-300 hover:text-white text-[11px] underline underline-offset-2 flex items-center gap-1 shrink-0"
            >
              <span>Open in new tab</span>
              <ExternalLink className="w-3 h-3" />
            </a>
          </div>
        </div>

      </div>
    </div>
  );
};
