import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Check, X, Crown, Zap, CheckCircle2, AlertCircle } from 'lucide-react';
import toast from 'react-hot-toast';
import { useTranslation } from 'react-i18next';
import { getLicenseInfo, activateLicense, deactivateLicense } from '../../services/api';
import ProBadge from '../ui/ProBadge';
import type { LicenseInfo } from '../../types/license';

export default function LicenseManager() {
  const { t } = useTranslation();
  const [licenseKey, setLicenseKey] = useState('');
  const queryClient = useQueryClient();
  
  // Fetch license info
  const { data: licenseData, isLoading } = useQuery<LicenseInfo>({
    queryKey: ['license', 'info'],
    queryFn: async () => {
      const response = await getLicenseInfo();
      return response.data; // Extract data from API response
    },
  });
  
  const license = licenseData; // licenseData is already the license object
  
  // Debug logging
  React.useEffect(() => {
    console.log('[LicenseManager] licenseData:', licenseData);
    console.log('[LicenseManager] license:', license);
    console.log('[LicenseManager] license?.is_active:', license?.is_active);
  }, [licenseData, license]);
  
  // Activate mutation
  const activateMutation = useMutation({
    mutationFn: (key: string) => activateLicense(key),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['license'] });
      toast.success(t('license.activation_success'));
      setLicenseKey('');
    },
    onError: (error: any) => {
      console.error('[License] Activation error:', error);

      // 🔒 SECURITY: Handle rate limiting and other errors
      if (error.response?.status === 429) {
        toast.error(
          error.response?.data?.message ||
          t('license.rate_limit_error', { defaultValue: 'Too many activation attempts. Please try again in 15 minutes.' })
        );
      } else {
        toast.error(error.response?.data?.message || t('license.activation_error'));
      }
    },
  });
  
  // Deactivate mutation
  const deactivateMutation = useMutation({
    mutationFn: () => deactivateLicense(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['license'] });
      toast.success(t('license.deactivation_success'));
    },
  });
  
  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    );
  }
  
  return (
    <div className="space-y-6">
      
      {/* LICENSE ACTIVATION SECTION */}
      <div className="bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-200 rounded-xl p-6 shadow-sm">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
              {t('license.activation_title')}
            </h3>
            <p className="text-sm text-gray-600 mt-1">{t('license.activation_subtitle')}</p>
          </div>
        </div>
        
        <div className="flex items-center gap-3">
          <input
            type="text"
            value={licenseKey}
            onChange={(e) => setLicenseKey(e.target.value)}
            placeholder="VH-PRO-YYYY-XXXX-XXXX-XXXX"
            disabled={activateMutation.isPending}
            className="flex-1 px-4 py-2.5 border border-blue-300 rounded-lg bg-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50"
          />
          <button
            onClick={() => activateMutation.mutate(licenseKey)}
            disabled={!licenseKey || activateMutation.isPending}
            className="px-6 py-2.5 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {activateMutation.isPending ? t('license.activating') : t('license.activate_button')}
          </button>
        </div>
      </div>
      
      {/* ACTIVE LICENSE STATUS (if license active) */}
      {license?.is_active && (
        <div className="bg-gradient-to-br from-green-50 to-emerald-50 border-2 border-green-300 rounded-xl p-6 shadow-sm">
          <div className="flex items-start justify-between">
            <div className="flex items-start gap-3">
              <div className="flex-shrink-0 w-12 h-12 bg-green-500 rounded-full flex items-center justify-center">
                <CheckCircle2 className="w-6 h-6 text-white" />
              </div>
              <div>
                <h3 className="text-lg font-bold text-green-900 mb-1">
                  {t('license.active_license')}
                </h3>
                <div className="space-y-1 text-sm text-green-800">
                  <p>
                    <span className="font-medium">{t('license.tier')}:</span>{' '}
                    <span className="font-bold uppercase">{license.tier_label}</span>
                  </p>
                  <p>
                    <span className="font-medium">{t('license.license_key')}:</span>{' '}
                    <code className="bg-white/50 px-2 py-0.5 rounded text-xs">{license.license_key}</code>
                  </p>
                  <p>
                    <span className="font-medium">{t('license.expires')}:</span>{' '}
                    {license.expires}
                  </p>
                </div>
              </div>
            </div>
            <button
              onClick={() => {
                if (confirm(t('license.deactivate_confirm'))) {
                  deactivateMutation.mutate();
                }
              }}
              disabled={deactivateMutation.isPending}
              className="px-4 py-2 text-sm font-medium text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-50"
            >
              {deactivateMutation.isPending ? t('license.deactivating') : t('license.deactivate_button')}
            </button>
          </div>
        </div>
      )}
      
      {/* UPGRADE TO PRO CARD - Only show if license is NOT active */}
      {!license?.is_active && (
        <div className="bg-gradient-to-br from-amber-50 via-yellow-50 to-amber-100 border-2 border-amber-300 rounded-xl p-6 shadow-lg">
          
          {/* Header */}
          <div className="text-center mb-6">
            <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-amber-400 to-yellow-500 rounded-full mb-4 shadow-md">
              <Crown className="w-8 h-8 text-white" />
            </div>
            <h2 className="text-2xl font-bold text-gray-900 mb-2">
              {t('license.upgrade_card_title')}
            </h2>
            <p className="text-gray-700">{t('license.upgrade_card_description')}</p>
          </div>
          
          {/* Pricing */}
          <div className="text-center mb-6 pb-6 border-b border-amber-300">
          <div className="flex items-center justify-center gap-4">
            <div className="text-left">
              <div className="text-sm text-gray-600 font-medium">{t('license.current_tier_free')}</div>
              <div className="text-lg font-bold text-gray-400 line-through">$0</div>
            </div>
            <Zap className="w-6 h-6 text-amber-600" />
            <div className="text-left">
              <div className="text-sm text-amber-800 font-bold flex items-center gap-1">
                <Crown className="w-4 h-4" />
                {t('license.tier_pro')}
              </div>
              <div className="text-4xl font-black text-amber-900">
                $29
                <span className="text-base font-normal text-gray-700">/ {t('license.per_year')}</span>
              </div>
            </div>
          </div>
          <p className="text-xs text-gray-600 mt-3">
            {t('license.price_details')}
          </p>
        </div>
        
        {/* FIRST CTA BUTTON - after pricing */}
        <a 
          href="https://bytebays.com/variation-hub/" 
          target="_blank" 
          rel="noopener noreferrer"
          className="w-full py-3 bg-gradient-to-r from-amber-500 to-yellow-600 text-white font-bold text-base rounded-lg hover:from-amber-600 hover:to-yellow-700 transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2 mb-6"
        >
          <Crown className="w-5 h-5" />
          {t('license.upgrade_card_title')}
        </a>
        
        {/* 2-COLUMN FEATURE COMPARISON TABLE */}
        <div className="bg-white/90 rounded-lg p-5 mb-6 border border-amber-200">
          <h3 className="text-lg font-bold text-gray-900 mb-4 text-center">{t('license.features_comparison')}</h3>
          
          <div className="grid grid-cols-3 gap-3">
            
            {/* Header Row */}
            <div className="text-xs font-bold text-gray-600 uppercase"></div>
            <div className="text-center">
              <span className="text-xs font-bold text-gray-600 uppercase">{t('license.free_tier')}</span>
            </div>
            <div className="text-center">
              <span className="inline-flex items-center gap-1 px-2 py-1 bg-amber-100 rounded-full">
                <Crown className="w-3 h-3 text-amber-700" />
                <span className="text-xs font-bold text-amber-900 uppercase">{t('license.pro_tier')}</span>
              </span>
            </div>
            
            {/* Excel-like Table */}
            <div className="text-sm font-medium text-gray-900">{t('features.excel_like')}</div>
            <div className="text-center">
              <Check className="w-5 h-5 text-green-600 mx-auto" />
            </div>
            <div className="text-center">
              <Check className="w-5 h-5 text-green-600 mx-auto" />
            </div>
            
            {/* CSV Export */}
            <div className="text-sm font-medium text-gray-900">{t('features.csv_export')}</div>
            <div className="text-center">
              <span className="text-xs text-gray-600">200 {t('features.rows')}</span>
            </div>
            <div className="text-center">
              <span className="text-xs font-bold text-amber-800">{t('features.unlimited')}</span>
            </div>
            
            {/* Bulk Operations */}
            <div className="text-sm font-medium text-gray-900">{t('features.bulk_operations')}</div>
            <div className="text-center">
              <span className="text-xs text-gray-600">10 {t('features.variations')}</span>
            </div>
            <div className="text-center">
              <span className="text-xs font-bold text-amber-800">{t('features.unlimited')}</span>
            </div>
            
            {/* XLSX Format */}
            <div className="text-sm font-medium text-gray-900">{t('features.xlsx_format')}</div>
            <div className="text-center">
              <X className="w-5 h-5 text-red-400 mx-auto" />
            </div>
            <div className="text-center">
              <Check className="w-5 h-5 text-green-600 mx-auto" />
            </div>
            
            {/* SKU Generator */}
            <div className="text-sm font-medium text-gray-900">{t('features.sku_generator')}</div>
            <div className="text-center">
              <X className="w-5 h-5 text-red-400 mx-auto" />
            </div>
            <div className="text-center">
              <Check className="w-5 h-5 text-green-600 mx-auto" />
            </div>
            
            {/* Attribute Manager */}
            <div className="text-sm font-medium text-gray-900">{t('features.attribute_manager')}</div>
            <div className="text-center">
              <X className="w-5 h-5 text-red-400 mx-auto" />
            </div>
            <div className="text-center">
              <Check className="w-5 h-5 text-green-600 mx-auto" />
            </div>
            
            {/* Performance Tools */}
            <div className="text-sm font-medium text-gray-900">{t('features.performance_tools')}</div>
            <div className="text-center">
              <X className="w-5 h-5 text-red-400 mx-auto" />
            </div>
            <div className="text-center">
              <Check className="w-5 h-5 text-green-600 mx-auto" />
            </div>
            
          </div>
        </div>
        
        {/* MARKETING DESCRIPTIONS - Expanded Features */}
        <div className="space-y-3 mb-6">
          
          {/* Excel-like Table View */}
          <div className="bg-white/70 rounded-lg p-4 border border-amber-200">
            <div className="flex items-start gap-3">
              <CheckCircle2 className="w-5 h-5 text-green-600 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <h4 className="font-bold text-gray-900 mb-1">{t('features.excel_like')}</h4>
                <p className="text-sm text-gray-700">{t('features.excel_like_desc')}</p>
              </div>
            </div>
          </div>
          
          {/* Unlimited CSV Export/Import */}
          <div className="bg-white/70 rounded-lg p-4 border border-amber-200">
            <div className="flex items-start gap-3">
              <Crown className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <h4 className="font-bold text-gray-900">{t('features.csv_unlimited')}</h4>
                  <ProBadge />
                </div>
                <p className="text-sm text-gray-700">{t('features.csv_unlimited_desc')}</p>
              </div>
            </div>
          </div>
          
          {/* Bulk Operations */}
          <div className="bg-white/70 rounded-lg p-4 border border-amber-200">
            <div className="flex items-start gap-3">
              <Crown className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <h4 className="font-bold text-gray-900">{t('features.bulk_operations')}</h4>
                  <ProBadge />
                </div>
                <p className="text-sm text-gray-700">{t('features.bulk_operations_desc')}</p>
              </div>
            </div>
          </div>
          
          {/* XLSX Format */}
          <div className="bg-white/70 rounded-lg p-4 border border-amber-200">
            <div className="flex items-start gap-3">
              <Crown className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <h4 className="font-bold text-gray-900">{t('features.xlsx_format')}</h4>
                  <ProBadge />
                </div>
                <p className="text-sm text-gray-700">{t('features.xlsx_format_desc')}</p>
              </div>
            </div>
          </div>
          
          {/* SKU Generator */}
          <div className="bg-white/70 rounded-lg p-4 border border-amber-200">
            <div className="flex items-start gap-3">
              <Crown className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <h4 className="font-bold text-gray-900">{t('features.sku_generator')}</h4>
                  <ProBadge />
                </div>
                <p className="text-sm text-gray-700">{t('features.sku_generator_desc')}</p>
              </div>
            </div>
          </div>
          
          {/* Attribute Manager */}
          <div className="bg-white/70 rounded-lg p-4 border border-amber-200">
            <div className="flex items-start gap-3">
              <Crown className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <h4 className="font-bold text-gray-900">{t('features.attribute_manager')}</h4>
                  <ProBadge />
                </div>
                <p className="text-sm text-gray-700">{t('features.attribute_manager_desc')}</p>
              </div>
            </div>
          </div>
          
          {/* Performance Optimization */}
          <div className="bg-white/70 rounded-lg p-4 border border-amber-200">
            <div className="flex items-start gap-3">
              <Crown className="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" />
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <h4 className="font-bold text-gray-900">{t('features.performance_tools')}</h4>
                  <ProBadge />
                </div>
                <p className="text-sm text-gray-700">{t('features.performance_tools_desc')}</p>
              </div>
            </div>
          </div>
          
        </div>
        
        {/* SECOND CTA BUTTON */}
        <a 
          href="https://bytebays.com/variation-hub/" 
          target="_blank" 
          rel="noopener noreferrer"
          className="w-full py-4 bg-gradient-to-r from-amber-500 to-yellow-600 text-white font-bold text-lg rounded-xl hover:from-amber-600 hover:to-yellow-700 transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2"
        >
          <Crown className="w-5 h-5" />
          {t('license.purchase_button')}
        </a>
        
        {/* Money-back Guarantee */}
        <p className="text-center text-sm text-gray-600 mt-4">
          ✓ {t('license.money_back_guarantee')}
        </p>
        
      </div>
      )}
      
    </div>
  );
}
