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

const PremiumModal = ({ configId = 'shop-explorer' }) => {
  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 Shop Explorer powerful features and take your store management to the next level!',
    premium_modal_button_text: 'Upgrade to Premium Now',
    premium_modal_button_url: 'https://wpazleen.com/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 - Use dynamic end time or fallback to 24 hours from now
  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');
  };

  return (
    <div className="premium-modal-container">
      {/* Header */}
      <div className="premium-header">
        <div className="premium-crown">
          <span>⭐</span>
        </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">
            <span>⏰</span>
            <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">
              <span className="value-icon">🚀</span>
              <div className="value-content">
                <h4>Advanced Export Features</h4>
                <p>Export unlimited products and orders with custom field mapping</p>
              </div>
            </div>
            <div className="value-prop">
              <span className="value-icon">🛡️</span>
              <div className="value-content">
                <h4>Bulk Operations</h4>
                <p>Perform bulk edits, imports, and advanced inventory management</p>
              </div>
            </div>
            <div className="value-prop">
              <span className="value-icon">⭐</span>
              <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>
        <span>→</span>
      </button>

      {/* Features Highlight - Only show when topbar is active */}
      {modalSettings.topbar_active && (
        <div className="premium-highlights">
          <div className="highlight-item">
            <span>🚀</span>
            <span>Advanced Export</span>
          </div>
          <div className="highlight-item">
            <span>🛡️</span>
            <span>Bulk Operations</span>
          </div>
          <div className="highlight-item">
            <span>⭐</span>
            <span>Priority Support</span>
          </div>
        </div>
      )}

    </div>
  );
};

export default PremiumModal;