const { useState, useEffect, useRef } = React;

function BookingModal() {
  const [isOpen, setIsOpen] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    program: 'Wedding / Muhurtham',
    date: '',
    notes: '',
  });

  // Custom Calendar State
  const [showCalendar, setShowCalendar] = useState(false);
  const [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
  const [currentYear, setCurrentYear] = useState(new Date().getFullYear());

  const cardRef = useRef(null);
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 });

  const handleMouseMove = (e) => {
    if (!cardRef.current) return;
    const rect = cardRef.current.getBoundingClientRect();
    setMousePos({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    });
  };

  const programsList = [
    { label: 'Single Reel Video (₹2,500)', group: 'Packages' },
    { label: 'Wedding Special 3 Reels (₹5,500)', group: 'Packages' },
    { label: 'Pro Camera Video (₹6,000)', group: 'Packages' },
    { label: 'Wedding Photography (₹13,000)', group: 'Packages' },
    { label: 'Wedding / Muhurtham', group: 'Events' },
    { label: 'Engagement Ceremony', group: 'Events' },
    { label: 'Bride-to-be / Groom-to-be', group: 'Events' },
    { label: 'Baby Shower & Maternity', group: 'Events' },
    { label: 'Birthday Party Event', group: 'Events' },
    { label: 'Luxury Car / Bike Delivery', group: 'Commercial' },
    { label: 'Brand Commercial / Ad Shoot', group: 'Commercial' },
    { label: 'Mobile 4K 60FPS Video Shoot', group: 'Mobile' },
    { label: 'Pro Camera Videography', group: 'Cinema' },
    { label: 'Full Day Photography', group: 'Photography' },
    { label: 'Other Custom Event', group: 'Custom' }
  ];

  const monthNames = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];

  useEffect(() => {
    const handleOpen = (e) => {
      if (e && e.detail && e.detail.program) {
        setFormData((prev) => ({ ...prev, program: e.detail.program }));
      }
      setIsOpen(true);
    };

    window.addEventListener('open-booking-modal', handleOpen);

    window.openReeloxBooking = (programName = 'Wedding / Muhurtham') => {
      setFormData((prev) => ({
        ...prev,
        program: programName,
      }));
      setIsOpen(true);
    };

    return () => {
      window.removeEventListener('open-booking-modal', handleOpen);
    };
  }, []);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  // Calendar Helpers
  const daysInMonth = (month, year) => new Date(year, month + 1, 0).getDate();
  const firstDayOfMonth = (month, year) => new Date(year, month, 1).getDay();

  const handlePrevMonth = (e) => {
    e.stopPropagation();
    if (currentMonth === 0) {
      setCurrentMonth(11);
      setCurrentYear(currentYear - 1);
    } else {
      setCurrentMonth(currentMonth - 1);
    }
  };

  const handleNextMonth = (e) => {
    e.stopPropagation();
    if (currentMonth === 11) {
      setCurrentMonth(0);
      setCurrentYear(currentYear + 1);
    } else {
      setCurrentMonth(currentMonth + 1);
    }
  };

  const handleSelectDate = (day) => {
    const monthFormatted = String(currentMonth + 1).padStart(2, '0');
    const dayFormatted = String(day).padStart(2, '0');
    const fullDate = `${currentYear}-${monthFormatted}-${dayFormatted}`;
    setFormData((prev) => ({ ...prev, date: fullDate }));
    setShowCalendar(false);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!formData.name || !formData.phone) {
      alert('Please enter your name and phone number.');
      return;
    }

    const text = 
`🎬 *NEW REELOX PRODUCTION BOOKING INQUIRY*
━━━━━━━━━━━━━━━━━━━━
👤 *Client Name:* ${formData.name}
📱 *Phone Number:* ${formData.phone}
🎉 *Package / Event:* ${formData.program}
📅 *Event Date:* ${formData.date ? formData.date : 'To be confirmed'}
${formData.notes ? `📝 *Specific Details:* ${formData.notes}` : ''}
━━━━━━━━━━━━━━━━━━━━
Sent from reeloxproduction.com`;

    const encoded = encodeURIComponent(text);
    const waUrl = `https://wa.me/919360701609?text=${encoded}`;
    window.open(waUrl, '_blank');
    setIsOpen(false);
  };

  if (!isOpen) return null;

  // Calendar Grid Generation
  const totalDays = daysInMonth(currentMonth, currentYear);
  const startDay = firstDayOfMonth(currentMonth, currentYear);
  const calendarCells = [];

  for (let i = 0; i < startDay; i++) {
    calendarCells.push(<div key={`empty-${i}`} className="cal-cell empty"></div>);
  }

  const today = new Date();
  for (let d = 1; d <= totalDays; d++) {
    const isPast = new Date(currentYear, currentMonth, d) < new Date(today.getFullYear(), today.getMonth(), today.getDate());
    const isSelected = formData.date === `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;

    calendarCells.push(
      <button
        type="button"
        key={`day-${d}`}
        disabled={isPast}
        onClick={(e) => {
          e.stopPropagation();
          handleSelectDate(d);
        }}
        className={`cal-cell day-cell ${isPast ? 'disabled' : ''} ${isSelected ? 'selected' : ''}`}
      >
        {d}
      </button>
    );
  }

  return (
    <div className="booking-modal-overlay" onClick={() => setIsOpen(false)}>
      <div 
        ref={cardRef}
        onMouseMove={handleMouseMove}
        className="booking-modal-card" 
        onClick={(e) => {
          e.stopPropagation();
          setShowCalendar(false);
        }}
        style={{
          '--mouse-x': `${mousePos.x}px`,
          '--mouse-y': `${mousePos.y}px`,
        }}
      >
        {/* Dynamic Cursor Spotlight Layer */}
        <div className="modal-spotlight-layer"></div>

        {/* Modal Close Button */}
        <button 
          className="booking-modal-close" 
          onClick={() => setIsOpen(false)}
          aria-label="Close modal"
        >
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>

        {/* Modal Header */}
        <div className="booking-modal-header">
          <h3 className="booking-modal-title font-serif">Reserve Your Shoot Slot</h3>
          <p className="booking-modal-sub">
            Fill out your details to lock in your date directly with our director on WhatsApp.
          </p>
        </div>

        {/* Booking Form */}
        <form onSubmit={handleSubmit} className="booking-form">
          
          {/* Row 1: Name & Phone Side-by-Side */}
          <div className="form-two-col">
            <div className="form-group">
              <label className="form-label">
                <span>Client Name</span>
                <span className="req-star">*</span>
              </label>
              <div className="input-wrap">
                <svg className="input-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                  <circle cx="12" cy="7" r="4"></circle>
                </svg>
                <input
                  type="text"
                  name="name"
                  required
                  value={formData.name}
                  onChange={handleChange}
                  placeholder="Your Name"
                  className="form-input with-icon"
                />
              </div>
            </div>

            <div className="form-group">
              <label className="form-label">
                <span>WhatsApp Phone</span>
                <span className="req-star">*</span>
              </label>
              <div className="input-wrap">
                <svg className="input-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
                </svg>
                <input
                  type="tel"
                  name="phone"
                  required
                  value={formData.phone}
                  onChange={handleChange}
                  placeholder="+91 Phone"
                  className="form-input with-icon"
                />
              </div>
            </div>
          </div>

          {/* Row 2: Program / Package & Event Date */}
          <div className="form-two-col">
            <div className="form-group">
              <label className="form-label">
                <span>Selected Package / Event</span>
                <span className="req-star">*</span>
              </label>
              <div className="input-wrap">
                <select
                  name="program"
                  value={formData.program}
                  onChange={handleChange}
                  className="form-select"
                >
                  {!programsList.some(p => p.label === formData.program) && (
                    <option value={formData.program} className="form-option">
                      {formData.program}
                    </option>
                  )}

                  {programsList.map((prog, idx) => (
                    <option key={idx} value={prog.label} className="form-option">
                      {prog.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Custom Aesthetic Date Picker */}
            <div className="form-group custom-date-group">
              <label className="form-label">
                <span>Select Event Date</span>
              </label>
              <div 
                className="input-wrap date-trigger-wrap" 
                onClick={(e) => {
                  e.stopPropagation();
                  setShowCalendar(!showCalendar);
                }}
              >
                <svg className="input-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                  <line x1="16" y1="2" x2="16" y2="6"></line>
                  <line x1="8" y1="2" x2="8" y2="6"></line>
                  <line x1="3" y1="10" x2="21" y2="10"></line>
                </svg>
                <div className={`custom-date-display ${formData.date ? 'has-val' : ''}`}>
                  {formData.date || "Choose on calendar"}
                </div>
                <div className="cal-dropdown-arrow">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="6 9 12 15 18 9"></polyline></svg>
                </div>
              </div>

              {/* Custom Dark Theme Aesthetic Calendar Dropdown */}
              {showCalendar && (
                <div className="custom-calendar-popover" onClick={(e) => e.stopPropagation()}>
                  <div className="cal-header">
                    <button type="button" onClick={handlePrevMonth} className="cal-nav-btn">‹</button>
                    <span className="cal-month-title">{monthNames[currentMonth]} {currentYear}</span>
                    <button type="button" onClick={handleNextMonth} className="cal-nav-btn">›</button>
                  </div>
                  
                  <div className="cal-weekdays">
                    <span>Su</span><span>Mo</span><span>Tu</span><span>We</span><span>Th</span><span>Fr</span><span>Sa</span>
                  </div>

                  <div className="cal-days-grid">
                    {calendarCells}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Row 3: Location / Notes */}
          <div className="form-group">
            <label className="form-label">
              <span>Location / Shoot Preferences</span>
            </label>
            <input
              type="text"
              name="notes"
              value={formData.notes}
              onChange={handleChange}
              placeholder="e.g. Kozhikode, Stage Reception, 4K 60FPS"
              className="form-input"
            />
          </div>

          {/* Submit Action */}
          <button type="submit" className="booking-submit-btn">
            <span>Send Direct Request to WhatsApp</span>
            <div className="btn-icon-circle">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                <line x1="5" y1="12" x2="19" y2="12"></line>
                <polyline points="12 5 19 12 12 19"></polyline>
              </svg>
            </div>
          </button>

          <div className="modal-privacy-footer">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
            <span>Direct WhatsApp reply from Reelox Production crew</span>
          </div>

        </form>

      </div>
    </div>
  );
}

// Mount Booking Modal Root Component
const modalMount = document.getElementById('react-modal-root');
if (modalMount) {
  const modalRoot = ReactDOM.createRoot(modalMount);
  modalRoot.render(<BookingModal />);
}
