import React, { useState, useEffect } from 'react';
import './PremiumModal.scss';

const PremiumModal = ({ configId = 'productdisplay', onClose }) => {
  const [timeLeft, setTimeLeft] = useState({
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0
  });

  const [modalSettings, setModalSettings] = useState({
    topbar_active: true,
    discount_end_time: null,
    premium_modal_offer_amount: '80% + OFF',
    premium_modal_header_title: 'Unlock Premium Power!',
    premium_modal_content: 'Upgrade now to unlock Product Display powerful features and take your site to the next level!',
    premium_modal_button_text: 'Upgrade to Premium Now',
    premium_modal_button_url: 'https://wpazleen.com/product-display-pricing/'
  });

  // Fetch modal settings from API
  useEffect(() => {
    const fetchModalSettings = async () => {
      try {
        const response = await fetch(`https://wpazleen.com/wp-json/wpx/v1/premium-modal-settings?config_id=${configId}`);
        if (response.ok) {
          const data = await response.json();
          if (data.success && data.data) {
            setModalSettings(data.data);
          }
        }
      } catch (error) {
        console.error('Failed to fetch modal settings:', error);
      }
    };

    fetchModalSettings();
  }, [configId]);

  // Countdown timer
  useEffect(() => {
    let targetDate;

    if (modalSettings.discount_end_time) {
      targetDate = new Date(modalSettings.discount_end_time);
    } else {
      targetDate = new Date();
      targetDate.setHours(targetDate.getHours() + 24);
    }

    const timer = setInterval(() => {
      const now = new Date().getTime();
      const distance = targetDate.getTime() - now;

      if (distance > 0) {
        setTimeLeft({
          days: Math.floor(distance / (1000 * 60 * 60 * 24)),
          hours: Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
          minutes: Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
          seconds: Math.floor((distance % (1000 * 60)) / 1000)
        });
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [modalSettings.discount_end_time]);

  const handleUpgrade = () => {
    window.open(modalSettings.premium_modal_button_url, '_blank');
  };

  const formatTime = (time) => {
    return time.toString().padStart(2, '0');
  };

  // Close on Escape key
  useEffect(() => {
    const handleEscape = (e) => {
      if (e.key === 'Escape' && onClose) {
        onClose();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [onClose]);

  return (
    <div className="premium-modal-overlay" onClick={onClose}>
      <div className="premium-modal-wrapper" onClick={(e) => e.stopPropagation()}>
        {onClose && (
          <button className="premium-modal-close" onClick={onClose} aria-label="Close modal">
            <i className="fas fa-times"></i>
          </button>
        )}

        <div className="premium-modal-container">
          {/* Header */}
          <div className="premium-header">
            <div className="premium-crown">
              <i className="fas fa-star"></i>
            </div>
            <h2>{modalSettings.premium_modal_header_title} 🚀</h2>
            <p>
              {modalSettings.premium_modal_content}
            </p>
          </div>

          {/* Conditional Offer Section - Show countdown only if topbar is active */}
          {modalSettings.topbar_active ? (
            <div className="premium-offer">
              <div className="premium-offer__badge">
                <i className="fas fa-clock"></i>
                <span>Limited Time Offer</span>
              </div>
              <div className="premium-countdown">
                <div className="countdown-item">
                  <span className="countdown-number">{formatTime(timeLeft.days)}</span>
                  <span className="countdown-label">Days</span>
                </div>
                <div className="countdown-separator">:</div>
                <div className="countdown-item">
                  <span className="countdown-number">{formatTime(timeLeft.hours)}</span>
                  <span className="countdown-label">Hours</span>
                </div>
                <div className="countdown-separator">:</div>
                <div className="countdown-item">
                  <span className="countdown-number">{formatTime(timeLeft.minutes)}</span>
                  <span className="countdown-label">Minutes</span>
                </div>
                <div className="countdown-separator">:</div>
                <div className="countdown-item">
                  <span className="countdown-number">{formatTime(timeLeft.seconds)}</span>
                  <span className="countdown-label">Seconds</span>
                </div>
              </div>
              <p className="premium-offer__text">
                🔥 <strong>{modalSettings.premium_modal_offer_amount}</strong> - Save hundreds of dollars!
              </p>
            </div>
          ) : (
            /* Basic Upgrade Section - Show when topbar is disabled */
            <div className="premium-basic-offer">
              <div className="premium-value-props">
                <div className="value-prop">
                  <i className="fas fa-rocket value-icon"></i>
                  <div className="value-content">
                    <h4>Supercharge Your Website</h4>
                    <p>Get access to 50+ premium features that will transform your site</p>
                  </div>
                </div>
                <div className="value-prop">
                  <i className="fas fa-shield-alt value-icon"></i>
                  <div className="value-content">
                    <h4>Advanced Security</h4>
                    <p>Protect your site with enterprise-level security features</p>
                  </div>
                </div>
                <div className="value-prop">
                  <i className="fas fa-star value-icon"></i>
                  <div className="value-content">
                    <h4>Priority Support</h4>
                    <p>Get help when you need it with our dedicated support team</p>
                  </div>
                </div>
              </div>
              {modalSettings.premium_modal_offer_amount && (
                <div className="premium-offer-highlight">
                  <span className="offer-badge">Special Offer</span>
                  <span className="offer-text">{modalSettings.premium_modal_offer_amount}</span>
                </div>
              )}
            </div>
          )}

          {/* CTA Button */}
          <button className="premium-cta" onClick={handleUpgrade}>
            <span>{modalSettings.premium_modal_button_text}</span>
            <i className="fas fa-arrow-right"></i>
          </button>

          {/* Features Highlight - Only show when topbar is active */}
          {modalSettings.topbar_active && (
            <div className="premium-highlights">
              <div className="highlight-item">
                <i className="fas fa-rocket"></i>
                <span>50+ Premium Features</span>
              </div>
              <div className="highlight-item">
                <i className="fas fa-shield-alt"></i>
                <span>Advanced Security</span>
              </div>
              <div className="highlight-item">
                <i className="fas fa-star"></i>
                <span>Priority Support</span>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default PremiumModal;