import { useState, useEffect } from 'react';
import Button from '../UI/Button';

export default function License() {
  const isPro    = Boolean(window.rescueFill?.isPro);
  const isAgency = Boolean(window.rescueFill?.isAgency);
  const [licenseKey, setLicenseKey] = useState('');
  const [status, setStatus] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState({ type: '', text: '' });
  const [savedKey, setSavedKey] = useState('');

  const apiBase = window.rescueFill?.apiUrl || '/wp-json/rescue/v1';
  const nonce = window.rescueFill?.nonce || '';
  const ajaxUrl = window.rescueFill?.ajaxUrl || '/wp-admin/admin-ajax.php';

  useEffect(() => {
    // Load current license status
    fetch(`${apiBase}/license/status`, {
      headers: { 'X-WP-Nonce': nonce },
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          setStatus(data.data?.status || '');
          setSavedKey(data.data?.license_key || '');
          if (data.data?.license_key) {
            // Mask the key for display
            const key = data.data.license_key;
            const masked = key.substring(0, 6) + '•'.repeat(key.length - 12) + key.substring(key.length - 6);
            setLicenseKey(masked);
          }
        }
      })
      .catch(() => {});
  }, [apiBase, nonce]);

  const handleActivate = async () => {
    if (!licenseKey.trim()) {
      setMessage({ type: 'error', text: 'Please enter your license key.' });
      return;
    }

    setLoading(true);
    setMessage({ type: '', text: '' });

    try {
      const formData = new FormData();
      formData.append('action', 'rfpro_activate_license');
      formData.append('license_key', licenseKey.trim());
      formData.append('nonce', nonce);

      const res = await fetch(ajaxUrl, {
        method: 'POST',
        headers: { 'X-WP-Nonce': nonce },
        body: formData,
      });

      const data = await res.json();

      if (data.success) {
        setStatus('valid');
        setSavedKey(licenseKey);
        setMessage({ type: 'success', text: 'License activated successfully!' });
        // Mask the key
        const key = licenseKey;
        const masked = key.substring(0, 6) + '•'.repeat(key.length - 12) + key.substring(key.length - 6);
        setLicenseKey(masked);
      } else {
        setMessage({ type: 'error', text: data.data?.message || 'Failed to activate license.' });
      }
    } catch (e) {
      setMessage({ type: 'error', text: 'Network error. Please try again.' });
    } finally {
      setLoading(false);
    }
  };

  const handleDeactivate = async () => {
    if (!window.confirm('Are you sure you want to deactivate your license?')) return;

    setLoading(true);
    setMessage({ type: '', text: '' });

    try {
      const formData = new FormData();
      formData.append('action', 'rfpro_deactivate_license');
      formData.append('nonce', nonce);

      const res = await fetch(ajaxUrl, {
        method: 'POST',
        headers: { 'X-WP-Nonce': nonce },
        body: formData,
      });

      const data = await res.json();

      if (data.success) {
        setStatus('');
        setSavedKey('');
        setLicenseKey('');
        setMessage({ type: 'success', text: 'License deactivated successfully.' });
      } else {
        setMessage({ type: 'error', text: data.data?.message || 'Failed to deactivate license.' });
      }
    } catch (e) {
      setMessage({ type: 'error', text: 'Network error. Please try again.' });
    } finally {
      setLoading(false);
    }
  };

  const proFeatures = [
    { icon: '🎯', name: 'Drag-Drop Funnel Builder' },
    { icon: '🔄', name: 'Multi-Step Sequences' },
    { icon: '📧', name: 'Brevo / SendGrid Integration' },
    { icon: '🔗', name: 'Webhooks & Zapier / Make' },
    { icon: '🌍', name: 'Location-Based Auto-Lists' },
    { icon: '📊', name: 'Advanced Analytics' },
    { icon: '🧪', name: 'A/B Testing' },
    { icon: '🎨', name: 'White-label (Agency)' },
  ];

  if (isPro) {
    return (
      <div className="max-w-4xl mx-auto space-y-8 animate-fade-in">
        <div>
          <h2 className="text-3xl font-extrabold text-slate-900">License</h2>
          <p className="text-slate-600 text-sm mt-1 font-medium">Manage your RescueFill Pro license.</p>
        </div>

        {/* Status Card */}
        <div className="bg-gradient-to-br from-emerald-50 to-green-50 border-2 border-emerald-200 rounded-2xl p-6">
          <div className="flex items-start gap-4">
            <div className="w-14 h-14 bg-emerald-500 rounded-xl flex items-center justify-center text-white text-2xl shrink-0 shadow-lg">
              ✓
            </div>
            <div className="flex-1">
              <h3 className="font-bold text-xl text-emerald-900">Pro License Active</h3>
              <p className="text-emerald-700 text-sm mt-1">
                All Pro features are unlocked and ready to use.
              </p>
              {savedKey && (
                <div className="mt-4 flex items-center gap-3">
                  <span className="text-xs font-semibold text-emerald-600 bg-white border border-emerald-200 px-3 py-1.5 rounded-lg">
                    License: {licenseKey}
                  </span>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Features Grid */}
        <div>
          <h3 className="font-bold text-lg text-slate-900 mb-4">Active Pro Features</h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {proFeatures.map(({ icon, name }) => (
              <div key={name} className="bg-white border border-slate-200 rounded-xl p-4 flex items-center gap-3 shadow-soft hover:shadow-medium transition-all">
                <span className="text-2xl">{icon}</span>
                <span className="text-sm font-semibold text-slate-700">{name}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Deactivate Button */}
        <div className="pt-4 border-t border-slate-200">
          <Button variant="secondary" onClick={handleDeactivate} loading={loading}>
            Deactivate License
          </Button>
        </div>
      </div>
    );
  }

  // Free version - upsell
  return (
    <div className="max-w-4xl mx-auto space-y-8 animate-fade-in">
      <div>
        <h2 className="text-3xl font-extrabold text-slate-900">Extend The Features</h2>
        <p className="text-slate-600 text-sm mt-1 font-medium">Unlock the full power of RescueFill with Pro.</p>
      </div>

      {message.text && (
        <div className={`rounded-xl px-4 py-3 text-sm font-medium ${
          message.type === 'success' 
            ? 'bg-emerald-50 border border-emerald-200 text-emerald-700' 
            : 'bg-red-50 border border-red-200 text-red-700'
        }`}>
          {message.text}
        </div>
      )}

      {/* License Input */}
      <div className="bg-white border-2 border-slate-200 rounded-2xl p-6 shadow-soft">
        <h3 className="font-bold text-lg text-slate-900 mb-4">Activate Your License</h3>
        <div className="flex flex-col sm:flex-row gap-3">
          <input
            type="text"
            value={licenseKey}
            onChange={(e) => setLicenseKey(e.target.value)}
            placeholder="Enter your license key"
            className="flex-1 border-2 border-slate-300 rounded-xl px-4 py-2.5 text-sm outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
            disabled={loading}
          />
          <Button 
            variant="primary" 
            onClick={handleActivate} 
            loading={loading}
            disabled={!licenseKey.trim()}
          >
            Activate License
          </Button>
        </div>
        <p className="text-xs text-slate-500 mt-3">
          Don't have a license key?{' '}
          <a 
            href="https://themefreex.com/rescuefill-pro" 
            target="_blank" 
            rel="noopener noreferrer"
            className="text-indigo-600 font-semibold hover:underline"
          >
            Get Pro →
          </a>
        </p>
      </div>

      {/* Pro Features Preview */}
      <div className="bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50 border-2 border-indigo-200 rounded-2xl p-8">
        <h3 className="font-bold text-xl text-slate-900 mb-6 text-center">What's Included in Pro</h3>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {proFeatures.map(({ icon, name }) => (
            <div key={name} className="bg-white border border-indigo-100 rounded-xl p-4 flex items-center gap-3 shadow-soft">
              <span className="text-2xl">{icon}</span>
              <span className="text-sm font-semibold text-slate-700">{name}</span>
            </div>
          ))}
        </div>

        {/* CTA */}
        <div className="mt-8 text-center">
          <a
            href="https://themefreex.com/rescuefill-pro"
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center justify-center gap-2 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-bold px-8 py-3.5 rounded-xl transition-all shadow-lg hover:shadow-xl hover:scale-105"
          >
            ⚡ Get RescueFill Pro
          </a>
          <p className="text-sm text-slate-500 mt-3 font-medium">
            14-day money-back guarantee · No monthly fees · Cancel anytime
          </p>
        </div>
      </div>
    </div>
  );
}
