import React, { useState } from 'react';
import { makeApiRequest } from '../common';
import { useTranslations } from '../hooks/useTranslation';

const FlexOrderPromoBanner = ({ 
  activeOrders, 
  onDismiss, 
  showClose = true, 
  customTitle = null, 
  customSubtitle = null,
  variant = 'horizontal',
  bullets = [],
  showAsButtons = false
}) => {
  const { t } = useTranslations();
  const [isInstalling, setIsInstalling] = useState(false);
  const [installationStatus, setInstallationStatus] = useState('');

  const assetsUrl = window?.archm_admin?.assets_url || '';
  const flexOrderUrl = window?.archm_admin?.flexorder_promo?.plugin_url || 'https://lnk.wppool.dev/gWV8px3';
  
  const isVertical = variant === 'vertical';

  // Reusable card styles following dashboard theme
  const cardStyle = {
    background: '#fff',
    borderRadius: '12px',
    border: '1px solid #E2E8F0',
    marginBottom: '24px',
    position: 'relative',
    display: 'flex',
    overflow: 'hidden'
  };

  const handleInstall = async () => {
    if (isInstalling) return;

    setIsInstalling(true);
    setInstallationStatus('Installing...');

    try {
      const response = await makeApiRequest('flexorder-install-plugin', 'POST');
      
      if (response.success) {
        setInstallationStatus(t('flexorder.modal.success'));
        setTimeout(() => {
          window.location.reload();
        }, 1500);
      } else {
        alert(response.message || 'Installation failed. Please try installing from the plugin search page.');
        setIsInstalling(false);
        setInstallationStatus('');
      }
    } catch (error) {
      alert('An error occurred during installation. Please try again.');
      setIsInstalling(false);
      setInstallationStatus('');
    }
  };

  const handleManageSmartly = () => {
    window.open(flexOrderUrl, '_blank');
  };

  return (
    <div 
      style={cardStyle} 
      className={isVertical 
        ? "arcm-flex-col" 
        : "arcm-flex-col md:arcm-flex-row arcm-p-5 md:arcm-p-8 arcm-gap-6 md:arcm-gap-10 arcm-items-center arcm-justify-between"
      }
    >
      {/* Close Button */}
      {showClose && (
        <button 
          onClick={onDismiss}
          style={{
            position: 'absolute',
            top: '12px',
            right: '12px',
            background: 'none',
            border: 'none',
            cursor: 'pointer',
            color: '#94A3B8',
            zIndex: 10
          }}
          id="archm-banner-close"
        >
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      )}

      {/* Vertical Image Header */}
      {isVertical && (
        <div style={{ width: '100%' }} className="arcm-p-5 md:arcm-p-8 arcm-pb-0">
          <div style={{ background: '#F8FAFC', borderRadius: '12px', padding: '20px', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <img 
              src={`${assetsUrl}/images/order-flex-img-1.svg`} 
              alt="Sync orders banner" 
              style={{ maxHeight: '150px', width: 'auto' }}
            />
          </div>
        </div>
      )}

      {/* Content Side */}
      <div 
        style={{ flex: 1, width: '100%' }} 
        className={isVertical ? "arcm-p-8 arcm-pt-6" : "arcm-p-0"}
      >
        {/* Badge */}
        <div style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: '6px',
          background: '#FF6B3A',
          color: '#fff',
          padding: '4px 12px',
          borderRadius: '100px',
          fontSize: '12px',
          fontWeight: '700',
          marginBottom: '16px'
        }}>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M6.5 1L1.5 7H5.5L4.5 11L9.5 5H5.5L6.5 1Z" fill="white" stroke="white" strokeLinejoin="round"/>
          </svg>
          {t('flexorder.pro_tip')}
        </div>

        {/* Title & Description */}
        <h2 style={{
          fontSize: '20px',
          fontWeight: '700',
          color: '#111827',
          margin: '0 0 8px',
          lineHeight: '1.3'
        }}>
          {customTitle ? customTitle : (activeOrders && activeOrders > 0 
            ? t('flexorder.banner.stop_managing_orders').replace('%s', activeOrders)
            : t('flexorder.banner.stop_managing')
          )}
        </h2>
        <p style={{
          fontSize: '15px',
          color: '#4B5563',
          margin: `0 0 ${bullets.length > 0 ? '16px' : '24px'}`,
          maxWidth: isVertical ? 'none' : '480px',
          lineHeight: '1.5'
        }}>
          {customSubtitle ? customSubtitle : t('flexorder.banner.desc')}
        </p>

        {/* Bullets */}
        {bullets.length > 0 && (
          <div style={{ marginBottom: '24px' }}>
            {bullets.map((bullet, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', marginBottom: '8px' }}>
                <svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg" style={{flexShrink: 0, marginTop: '2px'}}>
                  <path d="M7.50001 14.5C8.41943 14.5011 9.33001 14.3206 10.1794 13.9687C11.0289 13.6169 11.8004 13.1007 12.4497 12.4497C13.1007 11.8004 13.6169 11.0289 13.9687 10.1794C14.3206 9.33001 14.5011 8.41943 14.5 7.50001C14.5011 6.58059 14.3206 5.67001 13.9687 4.82058C13.6169 3.97115 13.1007 3.19962 12.4497 2.55031C11.8004 1.89936 11.0289 1.38313 10.1794 1.03128C9.33001 0.679419 8.41943 0.498872 7.50001 0.500005C6.58059 0.498872 5.67001 0.679419 4.82058 1.03128C3.97115 1.38313 3.19962 1.89936 2.55031 2.55031C1.89936 3.19962 1.38313 3.97115 1.03128 4.82058C0.679419 5.67001 0.498872 6.58059 0.500005 7.50001C0.498872 8.41943 0.679419 9.33001 1.03128 10.1794C1.38313 11.0289 1.89936 11.8004 2.55031 12.4497C3.19962 13.1007 3.97115 13.6169 4.82058 13.9687C5.67001 14.3206 6.58059 14.5011 7.50001 14.5Z" stroke="#4F46E5" strokeLinejoin="round"/>
                  <path d="M4.70007 7.50012L6.80007 9.60012L11.0001 5.40012" stroke="#4F46E5" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
                <span style={{ fontSize: '13px', color: '#374151', lineHeight: '1.4' }}>{bullet}</span>
              </div>
            ))}
          </div>
        )}

        {/* Actions */}
        <div 
          style={{ display: 'flex', alignItems: 'center', gap: showAsButtons ? '12px' : '24px', flexWrap: 'wrap' }}
          className={showAsButtons ? "arcm-flex-col md:arcm-flex-row arcm-w-full md:arcm-w-auto" : "arcm-flex-row"}
        >
          <button 
            onClick={handleManageSmartly}
            onMouseOver={(e) => {
              if (showAsButtons) {
                e.currentTarget.style.background = '#F3F2FD';
              } else {
                e.currentTarget.style.color = '#1D35AB';
                const svg = e.currentTarget.querySelector('path');
                if (svg) svg.style.stroke = '#1D35AB';
              }
            }}
            onMouseOut={(e) => {
              if (showAsButtons) {
                e.currentTarget.style.background = 'none';
              } else {
                e.currentTarget.style.color = '#3858E9';
                const svg = e.currentTarget.querySelector('path');
                if (svg) svg.style.stroke = '#3858E9';
              }
            }}
            className={showAsButtons ? "arcm-w-full md:arcm-w-auto" : ""}
            style={showAsButtons ? {
              background: 'none',
              border: '1px solid #3858E9',
              borderRadius: '8px',
              color: '#3858E9',
              fontSize: '14px',
              fontWeight: '700',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '8px',
              padding: '12px 20px',
              transition: 'all 0.2s',
              whiteSpace: 'nowrap'
            } : {
              background: 'none',
              border: 'none',
              color: '#3858E9',
              fontSize: '15px',
              fontWeight: '700',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              padding: 0,
              transition: 'color 0.2s'
            }}
          >
            {showAsButtons ? t('flexorder.banner.explore_live_sync') : t('flexorder.manage_orders_smartly')}
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M9 3L14 8M14 8L9 13M14 8H2" stroke="#3858E9" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transition: 'stroke 0.2s' }}/>
            </svg>
          </button>

          <button 
            onClick={handleInstall}
            disabled={isInstalling}
            onMouseOver={(e) => {
              if (isInstalling) return;
              if (showAsButtons) {
                e.currentTarget.style.background = '#E2E8F0';
              } else {
                e.currentTarget.style.color = '#3858E9';
              }
            }}
            onMouseOut={(e) => {
              if (isInstalling) return;
              if (showAsButtons) {
                e.currentTarget.style.background = '#F1F5F9';
              } else {
                e.currentTarget.style.color = '#1E293B';
              }
            }}
            className={showAsButtons ? "arcm-w-full md:arcm-w-auto" : ""}
            style={showAsButtons ? {
              background: '#F1F5F9',
              border: 'none',
              borderRadius: '8px',
              color: isInstalling ? '#64748B' : '#1E293B',
              fontSize: '14px',
              fontWeight: '600',
              cursor: isInstalling ? 'not-allowed' : 'pointer',
              padding: '12px 20px',
              transition: 'background 0.2s',
              whiteSpace: 'nowrap',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '8px'
            } : {
              background: 'none',
              border: 'none',
              color: isInstalling ? '#64748B' : '#1E293B',
              fontSize: '15px',
              fontWeight: '600',
              cursor: isInstalling ? 'not-allowed' : 'pointer',
              padding: 0,
              transition: 'color 0.2s',
              display: 'flex',
              alignItems: 'center',
              gap: '8px'
            }}
          >
            {isInstalling && (
              <svg className="arcm-animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle className="arcm-opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="arcm-opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
            )}
            {isInstalling ? t('flexorder.modal.installing') : installationStatus || t('flexorder.install_flexorder')}
          </button>
        </div>
      </div>

      {/* Horizontal Image Side (Desktop only for horizontal variant) */}
      {!isVertical && (
        <div style={{ flexShrink: 0 }} className="arcm-hidden md:arcm-block">
          <img 
            src={`${assetsUrl}/images/order-flex-img-1.svg`} 
            alt="Sync orders banner" 
            style={{ maxHeight: '180px', width: 'auto' }}
          />
        </div>
      )}
    </div>
  );
};

export default FlexOrderPromoBanner;
