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

const FlexOrderPromoModal = ({ isOpen, onClose, activeOrders, variant = 'archive' }) => {
  const { t } = useTranslations();
  const [isInstalling, setIsInstalling] = useState(false);
  const [installationStatus, setInstallationStatus] = useState('');
  
  const flexOrderUrl = window?.archm_admin?.flexorder_promo?.plugin_url || 'https://lnk.wppool.dev/gWV8px3';

  const isDashboard = variant === 'dashboard';

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

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

    try {
      const response = await makeApiRequest('flexorder-install-plugin', 'POST');
      
      if (response.success) {
        setInstallationStatus('Success!');
        // Refresh after a delay to show the active state
        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 (
    <Modal openModal={isOpen} toggleModal={onClose} outerClick={false} innerClassName="!arcm-max-w-[550px]">
      {{
        header: (
          <div className="arcm-text-center arcm-px-2 arcm-pt-1">
            <div style={{color: '#111827', fontSize: '18px', fontWeight: '700', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px', flexWrap: 'wrap'}}>
              <span style={{fontSize: '24px', lineHeight: '1', display: 'inline-flex', alignItems: 'center'}}>
                {isDashboard ? '👏' : '🎉'}
              </span> 
              <span style={{lineHeight: '1.2', display: 'inline-flex', alignItems: 'center', textAlign: 'center'}}>
                {isDashboard ? t('flexorder.modal.archiving_well') : t('flexorder.modal.congratulations')}
              </span>
            </div>
            {isDashboard ? (
              <p style={{color: '#6B7280', fontSize: '13px', marginTop: '6px', fontWeight: '500'}}>
                {t('flexorder.modal.but')}
              </p>
            ) : (
              <p style={{color: '#4B5563', fontSize: '13px', marginTop: '4px'}}>
                {t('flexorder.modal.archived_success')}
              </p>
            )}
          </div>
        ),
        body: (
          <div className="arcm-mt-1 arcm-mb-2">
            <h2 className="arcm-text-lg md:arcm-text-xl" style={{color: '#111827', fontWeight: '700', textAlign: 'center', lineHeight: '1.4', margin: '0 0 20px'}}>
              {isDashboard 
                ? t('flexorder.modal.how_managing').replace('%s', activeOrders)
                : t('flexorder.modal.how_handle').replace('%s', activeOrders)
              }
            </h2>

            <div style={{background: '#F3F2FD', borderRadius: '12px', padding: '18px', marginBottom: '8px'}}>
              <p style={{color: '#4F46E5', fontWeight: '700', marginBottom: '14px', fontSize: '15px'}}>
                {t('flexorder.modal.smart_way')}
              </p>
              {[
                t('flexorder.modal.feature_1'),
                t('flexorder.modal.feature_2'),
                t('flexorder.modal.feature_3'),
                t('flexorder.modal.feature_4'),
              ].map((feature, i) => (
                <div key={i} style={{display: 'flex', alignItems: 'flex-start', gap: '10px', marginBottom: '10px'}}>
                  <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.5'}}>{feature}</span>
                </div>
              ))}
            </div>
          </div>
        ),
        footer: (
          <div className="arcm-pb-2">
            <div className="arcm-flex arcm-flex-col sm:arcm-flex-row arcm-gap-3 arcm-mb-4">
              <button
                onClick={handleManageSmartly}
                style={{flex: 1, background: '#3858E9', color: 'white', border: 'none', borderRadius: '8px', padding: '12px 20px', fontWeight: '600', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', transition: 'background 0.2s', fontSize: '14px', whiteSpace: 'nowrap'}}
                id="archm-flexorder-manage-btn"
                onMouseOver={(e) => e.currentTarget.style.background = '#2846cc'}
                onMouseOut={(e) => e.currentTarget.style.background = '#3858E9'}
              >
                {t('flexorder.manage_orders_smartly')}
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M11.25 3.75L17.5 10M17.5 10L11.25 16.25M17.5 10H2.5" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
              <button
                onClick={handleInstall}
                disabled={isInstalling}
                style={{flex: 1, background: '#F8FAFC', color: isInstalling ? '#64748B' : '#1E293B', border: '1px solid #E2E8F0', borderRadius: '8px', padding: '12px 16px', fontWeight: '600', cursor: isInstalling ? 'not-allowed' : 'pointer', fontSize: '14px', transition: 'all 0.2s', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px'}}
                id="archm-flexorder-install-btn"
                onMouseOver={(e) => { if (!isInstalling) { e.currentTarget.style.background = '#F1F5F9'; e.currentTarget.style.borderColor = '#CBD5E1'; } }}
                onMouseOut={(e) => { if (!isInstalling) { e.currentTarget.style.background = '#F8FAFC'; e.currentTarget.style.borderColor = '#E2E8F0'; } }}
              >
                {isInstalling ? t('flexorder.modal.installing') : installationStatus === 'Success!' ? t('flexorder.modal.success') : t('flexorder.install_flexorder')}
              </button>
            </div>
            <div style={{textAlign: 'center'}}>
              <button
                onClick={onClose}
                style={{background: 'none', border: 'none', color: '#6B7280', cursor: 'pointer', fontSize: '13px', fontWeight: '500', transition: 'color 0.2s'}}
                id="archm-flexorder-close-btn"
                onMouseOver={(e) => e.target.style.color = '#374151'}
                onMouseOut={(e) => e.target.style.color = '#6B7280'}
              >
                {t('flexorder.modal.close')}
              </button>
            </div>
          </div>
        ),
      }}
    </Modal>
  );
};

export default FlexOrderPromoModal;
