import { useEffect, useState } from 'react';

const defaultHomeData = typeof window !== 'undefined' ? window.wowextHome || {} : {};

function StatusBadge({ status }) {
  const labels = {
    active: 'Active',
    inactive: 'Inactive',
    not_installed: 'Not installed',
    marketplace: 'wowextensions.com',
  };
  return <span className={`wowext-badge wowext-badge--${status}`}>{labels[status] || status}</span>;
}

function ExtensionIcon({ slug }) {
  const common = { width: 56, height: 56, viewBox: '0 0 24 24', fill: 'none', xmlns: 'http://www.w3.org/2000/svg', 'aria-hidden': true };
  if (slug === 'role_based_pricing') {
    return (
      <svg {...common}>
        <path
          d="M12 2H2v10l9.3 9.3a2 2 0 0 0 2.8 0l6.4-6.4a2 2 0 0 0 0-2.8L12 2Z"
          stroke="currentColor"
          strokeWidth="1.75"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
        <path d="M7 7h.01" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" />
        <path d="M12 6v6M9 9h6" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
      </svg>
    );
  }
  if (slug === 'one_page_checkout') {
    return (
      <svg {...common}>
        <circle cx="9" cy="21" r="1.5" fill="currentColor" stroke="none" />
        <circle cx="20" cy="21" r="1.5" fill="currentColor" stroke="none" />
        <path d="M1 1h4l2.7 13.4a2 2 0 0 0 2 1.6h9.7a2 2 0 0 0 2-1.6L23 6H6" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M12 3v4M10 5h4" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
      </svg>
    );
  }
  if (slug === 'wow_checkout_field_editor' || slug === 'wc_checkout_field_editor') {
    return (
      <svg {...common} viewBox="0 0 24 24">
        <path d="M4 6h16M4 10h10M4 14h7M4 18h10" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
        <rect x="14" y="12" width="6" height="6" rx="1" stroke="currentColor" strokeWidth="1.75" />
        <path d="M16 12V9a2 2 0 0 1 2-2h0" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
      </svg>
    );
  }
  if (slug === 'wow_subscription') {
    return (
      <svg {...common} viewBox="0 0 24 24">
        <path d="M12 3v3M12 18v3" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
        <path d="M4.2 8.2a7 7 0 0 0 1.1 7.1 7 7 0 0 0 9.9 0 7 7 0 0 0 1-7.1" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
        <path d="M4.2 8.2 7.5 5.5a7 7 0 0 1 9 0l3.3 2.7" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
      </svg>
    );
  }
  if (slug === 'wc_variation_swatches') {
    return (
      <svg {...common} viewBox="0 0 24 24">
        <circle cx="8" cy="9" r="3" stroke="currentColor" strokeWidth="1.5" fill="currentColor" fillOpacity="0.15" />
        <circle cx="16" cy="9" r="3" stroke="currentColor" strokeWidth="1.5" fill="currentColor" fillOpacity="0.35" />
        <circle cx="12" cy="16" r="3" stroke="currentColor" strokeWidth="1.5" fill="currentColor" fillOpacity="0.55" />
      </svg>
    );
  }
  if (slug === 'wc_minmax_quantities') {
    return (
      <svg {...common} viewBox="0 0 24 24">
        <path d="M8 4v16M4 8l4-4 4 4" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M16 20V4M20 16l-4 4-4-4" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  }
  if (slug === 'wc_sales_notifications') {
    return (
      <svg {...common} viewBox="0 0 24 24">
        <path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 7h18s-3 0-3-7" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M9.1 20a2 2 0 0 0 3.8 0" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
        <path d="M4 2v2M2 4h2M5 1l-1.5 1.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      </svg>
    );
  }
  if (slug === 'wc_shipment_tracking') {
    return (
      <svg {...common} viewBox="0 0 24 24">
        <rect x="2" y="7" width="15" height="10" rx="1" stroke="currentColor" strokeWidth="1.75" />
        <path d="M17 9h2l3 2v3h-3" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
        <circle cx="7.5" cy="19" r="1.5" fill="currentColor" />
        <circle cx="18" cy="19" r="1.5" fill="currentColor" />
      </svg>
    );
  }
  return (
    <svg {...common}>
      <path d="m12 2 3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function categoryLabel(builtIn) {
  return builtIn ? 'Manage' : 'Add-on';
}

export default function FeatureCard({ extension, onStatusChange, onNotify, apiConfig, onboardingMode = false }) {
  const data = apiConfig || defaultHomeData;
  const S = data.strings || {};
  const [busy, setBusy] = useState(false);
  const [confirmIntent, setConfirmIntent] = useState(null);

  useEffect(() => {
    if (!confirmIntent) return undefined;
    function onKey(e) {
      if (e.key === 'Escape' && !busy) {
        setConfirmIntent(null);
      }
    }
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [confirmIntent, busy]);

  const { slug, title, description, status, settingsUrl, pricingUrl, pluginFile, builtIn, marketplace } = extension;
  const isActive = status === 'active';
  const isNotInstalled = status === 'not_installed';
  const isMarketplace = !!marketplace;

  function notify(message, type) {
    if (message && typeof onNotify === 'function') {
      onNotify(message, type);
    } else if (message && type === 'error') {
      window.alert(message);
    }
  }

  async function pluginAction(action, extra = {}) {
    if (busy) return false;

    setBusy(true);
    try {
      const body = new URLSearchParams();
      body.append('action', action);
      body.append('nonce', data.nonce);
      body.append('slug', slug);
      Object.entries(extra).forEach(([k, v]) => body.append(k, v));

      const res = await fetch(data.ajaxUrl, { method: 'POST', body });
      const json = await res.json();

      if (json.success) {
        if (json.data?.settingsAssets) {
          if (typeof window.wowextMergeSettingsAssets === 'function') {
            window.wowextMergeSettingsAssets(json.data.settingsAssets);
          }
          if (typeof window.wowextEnsureSettingsAssets === 'function') {
            window.wowextEnsureSettingsAssets().catch(() => {});
          }
        }
        let newStatus =
          action === 'wowexfow_deactivate_plugin'
            ? 'inactive'
            : action === 'wowexfow_activate_plugin'
              ? 'active'
              : action === 'wowexfow_toggle_feature'
                ? (json.data && json.data.status) || (extra.enabled === 'yes' ? 'active' : 'inactive')
                : json.data && json.data.status;
        if (!newStatus) {
          notify(json.data?.message || 'Unexpected response.', 'error');
          return false;
        }
        onStatusChange(slug, newStatus);
        const okMsg =
          (json.data && json.data.message) ||
          (action === 'wowexfow_activate_plugin'
            ? 'Plugin activated.'
            : action === 'wowexfow_deactivate_plugin'
              ? 'Plugin deactivated.'
              : 'Done.');
        notify(okMsg, 'success');
        return true;
      }
      notify(json.data?.message || 'Action failed.', 'error');
      return false;
    } catch {
      notify(S.networkError || 'Network error. Please try again.', 'error');
      return false;
    } finally {
      setBusy(false);
    }
  }

  function handleInstall() {
    if (busy) return;
    if (isMarketplace) return;
    if (isNotInstalled) return;
    setConfirmIntent('enable');
  }

  function handleUninstall() {
    if (busy || !isActive) return;
    setConfirmIntent('disable');
  }

  function closeConfirm() {
    if (!busy) setConfirmIntent(null);
  }

  async function handleConfirm() {
    if (!confirmIntent) return;
    if (confirmIntent === 'enable') {
      if (builtIn) await pluginAction('wowexfow_toggle_feature', { enabled: 'yes' });
      else if (pluginFile) await pluginAction('wowexfow_activate_plugin', { plugin_file: pluginFile });
    } else {
      if (builtIn) await pluginAction('wowexfow_toggle_feature', { enabled: 'no' });
      else if (pluginFile) await pluginAction('wowexfow_deactivate_plugin', { plugin_file: pluginFile });
    }
    setConfirmIntent(null);
  }

  const confirmTitle =
    confirmIntent === 'enable'
      ? S.confirmEnableTitle || 'Enable this extension?'
      : S.confirmDisableTitle || 'Turn off this extension?';
  const confirmBody =
    confirmIntent === 'enable'
      ? builtIn
        ? S.confirmEnableBodyCore || ''
        : S.confirmEnableBodyAddon || ''
      : builtIn
        ? S.confirmDisableBodyCore || ''
        : S.confirmDisableBodyAddon || '';

  const canInstall = !isMarketplace && (isNotInstalled ? !!pricingUrl : !isActive && (builtIn || !!pluginFile));
  const canUninstall = isActive && (builtIn || !!pluginFile) && !isMarketplace;

  const cat = categoryLabel(!!builtIn);

  const primaryCta = isActive && settingsUrl && !onboardingMode ? (
    <a href={settingsUrl} className="wowext-feature-card__action-outline">
      Open
    </a>
  ) : isMarketplace && isNotInstalled && pricingUrl ? (
    <a
      href={pricingUrl}
      className="wowext-feature-card__action-outline"
      target="_blank"
      rel="noopener noreferrer"
    >
      Upgrade
    </a>
  ) : isNotInstalled && pricingUrl ? (
    <a href={pricingUrl} className="wowext-feature-card__action-outline" target="_blank" rel="noopener noreferrer">
      Get extension
    </a>
  ) : canInstall && !isNotInstalled ? (
    <button type="button" className="wowext-feature-card__action-outline" onClick={handleInstall} disabled={busy}>
      Enable
    </button>
  ) : null;

  const showFooter = canUninstall || primaryCta;

  return (
    <>
      <article
        className={`wowext-feature-card wowext-feature-card--${slug}${isMarketplace ? ' wowext-feature-card--marketplace' : ''}${
          isNotInstalled && !isMarketplace ? ' wowext-feature-card--disabled' : ''
        }${onboardingMode ? ' wowext-feature-card--onboarding' : ''}`}
      >
        <div className="wowext-feature-card__media">
          <span className="wowext-feature-card__category">{cat}</span>

          <div className="wowext-feature-card__media-art" aria-hidden="true">
            <span className="wowext-feature-card__blob wowext-feature-card__blob--a" />
            <span className="wowext-feature-card__blob wowext-feature-card__blob--b" />
            <span className="wowext-feature-card__blob wowext-feature-card__blob--c" />
            <div className="wowext-feature-card__icon-wrap">
              <ExtensionIcon slug={slug} />
            </div>
          </div>
        </div>

        <div className="wowext-feature-card__body">
          <h3 className="wowext-feature-card__title">{title}</h3>
          <div className="wowext-feature-card__meta">
            <StatusBadge status={isMarketplace ? 'marketplace' : status} />
          </div>
          <p className="wowext-feature-card__desc">{description}</p>
        </div>

        {showFooter && (
          <div className={`wowext-feature-card__footer${onboardingMode ? ' wowext-feature-card__footer--onboarding' : ''}`}>
            {!onboardingMode && canUninstall && (
              <button
                type="button"
                className="wowext-feature-card__text-action"
                onClick={handleUninstall}
                disabled={busy}
              >
                Turn off
              </button>
            )}
            <div className="wowext-feature-card__footer-cta">
              {onboardingMode && canUninstall && (
                <button
                  type="button"
                  className="wowext-feature-card__text-action wowext-feature-card__text-action--right"
                  onClick={handleUninstall}
                  disabled={busy}
                >
                  Turn off
                </button>
              )}
              {primaryCta}
            </div>
          </div>
        )}
      </article>

      {confirmIntent && (
        <div className="wowext-home-modal-backdrop" role="presentation" onClick={closeConfirm}>
          <div
            className="wowext-home-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="wowext-home-confirm-title"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 id="wowext-home-confirm-title" className="wowext-home-modal__title">
              {confirmTitle}
            </h2>
            <p className="wowext-home-modal__extension-name">{title}</p>
            {confirmBody ? <p className="wowext-home-modal__body">{confirmBody}</p> : null}
            <div className="wowext-home-modal__actions">
              <button type="button" className="wowext-home-modal__btn wowext-home-modal__btn--secondary" onClick={closeConfirm} disabled={busy}>
                {S.cancelButton || 'Cancel'}
              </button>
              <button
                type="button"
                className="wowext-home-modal__btn wowext-home-modal__btn--primary"
                onClick={handleConfirm}
                disabled={busy}
                aria-busy={busy}
              >
                {busy ? '…' : S.confirmButton || 'Confirm'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
