// src/app/components/admin/blocks/PricingSection.tsx

'use client';

import { motion } from 'framer-motion';
import { Check, Star, Zap, ArrowRight, Users, Sparkles, ShoppingCart, Eye } from 'lucide-react';
import { useState, useEffect } from 'react';
import { PricingSectionProps, PricingPackage } from '@/lib/page-builder/types';
import CustomPlanModal from './CustomPlanModal';
import PricingSectionSkeleton from './PricingSkeletons/PricingSectionSkeleton';
import PricingSectionToggleLoading from './PricingSkeletons/PricingSectionToggleLoading';
import PricingSectionError from './PricingSkeletons/PricingSectionError';
import PricingSectionEmpty from './PricingSkeletons/PricingSectionEmpty';
import Link from 'next/link';
import { useCart } from '@/hooks/useCart';
import toast from 'react-hot-toast';

// Sort packages to put popular one in second position
const sortPackagesByPopular = (packages: PricingPackage[]): PricingPackage[] => {
  if (packages.length <= 2) return packages;
  
  const popularPackage = packages.find(pkg => pkg.is_popular);
  const otherPackages = packages.filter(pkg => !pkg.is_popular);
  
  if (!popularPackage) return packages;
  
  return [
    otherPackages[0] || popularPackage,
    popularPackage,
    ...otherPackages.slice(1)
  ];
};

// Default mock data
const getDefaultPackages = (type: 'standard' | 'special_niche'): PricingPackage[] => {
  if (type === 'standard') {
    return [
      {
        id: 'pkg-starter-dummy',
        name: 'Starter',
        slug: 'starter-package',
        description: 'Perfect for businesses starting with guest posting',
        package_type: 'standard',
        base_price: '997.00',
        sale_price: null,
        features: [
          '5 Guest Posts Total',
          'DA 40-80 Authority Sites',
          '3000+ Words Quality Content',
          'Dofollow Links',
          '7-Day Delivery',
          'Basic Images Included',
          '30-Day Link Monitoring',
          'Money-Back Guarantee'
        ],
        status: 'active',
        is_popular: false,
        is_featured: false
      },
      {
        id: 'pkg-growth-dummy',
        name: 'Growth',
        slug: 'growth-package',
        description: 'Most popular for serious SEO growth & results',
        package_type: 'standard',
        base_price: '1897.00',
        sale_price: null,
        features: [
          '10 Guest Posts Total',
          'DA 40-90 Authority Sites',
          '4000+ Words Premium Content',
          'Dofollow + Contextual Links',
          '5-Day Delivery',
          'Premium Images + Infographics',
          '45-Day Link Monitoring',
          'Priority Support',
          'Content Outline Approval',
          '2x Faster Results'
        ],
        status: 'active',
        is_popular: true,
        is_featured: true
      },
      {
        id: 'pkg-agency-dummy',
        name: 'Agency',
        slug: 'agency-package',
        description: 'Maximum exposure for agencies & established businesses',
        package_type: 'standard',
        base_price: '3497.00',
        sale_price: null,
        features: [
          '20 Guest Posts Total',
          'DA 40-90+ Premium Sites',
          '5000+ Words Elite Content',
          'Dofollow + Contextual Links',
          '3-Day Express Delivery',
          'Custom Graphics + Featured Images',
          '60-Day Link Monitoring',
          'Dedicated Account Manager',
          'Content Strategy Included',
          'Performance Reporting',
          'White-Label Ready'
        ],
        status: 'active',
        is_popular: false,
        is_featured: false
      }
    ];
  } else {
    return [
      {
        id: 'pkg-crypto-dummy',
        name: 'Crypto Authority',
        slug: 'crypto-authority-package',
        description: 'Premium guest posting on top cryptocurrency websites',
        package_type: 'special_niche',
        base_price: '12999.00',
        sale_price: '11999.00',
        features: [
          '5 Crypto Guest Posts',
          'DA 60+ Crypto Authority Sites',
          'Crypto Expert Writers',
          'Industry-Specific Content',
          '7-Day Delivery',
          'Crypto-Focused Outreach',
          '60-Day Link Monitoring',
          'Crypto Niche Specialists',
          'Exchange & Wallet Coverage',
          'Blockchain Technology Focus'
        ],
        status: 'active',
        is_popular: true,
        is_featured: true
      },
      {
        id: 'pkg-cbd-dummy',
        name: 'CBD Premium',
        slug: 'cbd-premium-package',
        description: 'High-authority CBD and wellness website placements',
        package_type: 'special_niche',
        base_price: '14999.00',
        sale_price: '13999.00',
        features: [
          '8 CBD Guest Posts',
          'DA 50+ Health & CBD Sites',
          'CBD Content Specialists',
          'Medical Review Included',
          'FDA Compliance Check',
          'Health Authority Backlinks',
          '90-Day Link Monitoring',
          'Wellness Industry Focus',
          'Natural Health Outreach',
          'Supplement Authority Sites'
        ],
        status: 'active',
        is_popular: false,
        is_featured: true
      },
      {
        id: 'pkg-casino-dummy',
        name: 'Gambling Elite',
        slug: 'gambling-elite-package',
        description: 'Exclusive access to top gambling and casino websites',
        package_type: 'special_niche',
        base_price: '19999.00',
        sale_price: '17999.00',
        features: [
          '10 Gambling Posts',
          'DA 70+ Casino Authority Sites',
          'Gambling Industry Experts',
          'Regulatory Compliance Check',
          'High-Risk Content Specialists',
          '120-Day Link Monitoring',
          'Casino News Sites',
          'Poker & Betting Coverage',
          'Gaming Authority Backlinks',
          'Dedicated Risk Manager'
        ],
        status: 'active',
        is_popular: false,
        is_featured: false
      }
    ];
  }
};

// Hook to fetch packages
function usePackages(props: PricingSectionProps) {
  const [packages, setPackages] = useState<PricingPackage[]>([]);
  const [packageType, setPackageType] = useState<'standard' | 'special_niche'>(
    props.defaultPackageType || 'standard'
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [retryCount, setRetryCount] = useState(0);

  const fetchPackages = async () => {
    setPackages([]);
    setLoading(true);
    setError(null);
    
    try {
      if (props.packages && props.packages.length > 0) {
        await new Promise(resolve => setTimeout(resolve, 500));
        const filtered = props.packages.filter(p => p.package_type === packageType);
        const sorted = sortPackagesByPopular(filtered);
        setPackages(sorted);
        setLoading(false);
        return;
      }

      if (props.source === 'mock' && props.mockPackages) {
        await new Promise(resolve => setTimeout(resolve, 800));
        const filtered = props.mockPackages.filter(p => p.package_type === packageType);
        const sorted = sortPackagesByPopular(filtered);
        setPackages(sorted);
        setLoading(false);
        return;
      }

      if (props.source === 'api') {
        const endpoint = props.apiEndpoint || '/api/frontend/packages';
        const response = await fetch(`${endpoint}?type=${packageType}`);
        
        if (!response.ok) {
          throw new Error(`Failed to fetch packages: ${response.status}`);
        }
        
        const result = await response.json();
        const packagesData = result.data || result.packages || result;
        
        if (Array.isArray(packagesData) && packagesData.length > 0) {
          const sorted = sortPackagesByPopular(packagesData);
          setPackages(sorted);
        } else {
          setPackages(getDefaultPackages(packageType));
        }
        setLoading(false);
        return;
      }

      await new Promise(resolve => setTimeout(resolve, 600));
      setPackages(getDefaultPackages(packageType));
      setLoading(false);
      
    } catch (err) {
      console.error('Failed to load packages:', err);
      setError(err instanceof Error ? err.message : 'Failed to load packages');
      setPackages(getDefaultPackages(packageType));
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPackages();
  }, [packageType, props.source, props.apiEndpoint, props.packages, props.mockPackages, retryCount]);

  const handleRetry = () => {
    setRetryCount(prev => prev + 1);
  };

  return { packages, packageType, setPackageType, loading, error, handleRetry };
}

export default function PricingSection(props: PricingSectionProps) {
  const {
    id,
    className = '',
    title = 'Choose Your Growth Plan',
    description = 'Scale your SEO with our proven guest posting packages.',
    showToggle = true,
    showCustomPlanCTA = true,
  } = props;

  const [isCustomModalOpen, setIsCustomModalOpen] = useState(false);
  const [isAddingToCart, setIsAddingToCart] = useState<string | null>(null);
  const { packages, packageType, setPackageType, loading, error, handleRetry } = usePackages(props);
  const { addPackage } = useCart();

  const getIcon = (pkg: PricingPackage) => {
    if (pkg.package_type === 'special_niche') return Sparkles;
    if (pkg.is_popular) return Star;
    if (pkg.name.toLowerCase().includes('agency')) return Users;
    return Zap;
  };

  const handleAddToCart = async (pkg: PricingPackage) => {
    setIsAddingToCart(pkg.id);
    
    // Add slight delay for better UX
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const finalPrice = pkg.sale_price ? parseFloat(pkg.sale_price) : parseFloat(pkg.base_price);
    
    addPackage({
      packageId: pkg.id,
      packageSlug: pkg.slug,
      packageType: pkg.package_type,
      name: pkg.name,
      description: pkg.description,
      features: pkg.features,
      price: finalPrice,
      quantity: 1,
      contentService: false,
      assignedWebsiteIds: [],
    });
    
    toast.success(`${pkg.name} added to cart!`, {
      duration: 3000,
      position: 'bottom-right',
      icon: '🛒',
    });
    
    setIsAddingToCart(null);
  };

  const fadeInUp = {
    initial: { y: 60, opacity: 0 },
    animate: { y: 0, opacity: 1 },
  };

  const stagger = {
    animate: {
      transition: {
        staggerChildren: 0.15,
      },
    },
  };

  const getCardStyles = (pkg: PricingPackage) => {
    if (pkg.is_popular) {
      return {
        background: 'bg-gradient-to-br from-orange-400 to-red-500',
        border: 'border-0',
        text: 'text-white',
        iconBg: 'bg-white/20',
        featureText: 'text-white',
        priceText: 'text-white',
        viewDetailsBtn: 'bg-white/10 text-white hover:bg-white/20 border border-white/30 flex-1',
        addToCartBtn: 'bg-white text-gray-900 hover:bg-gray-50 hover:scale-105',
        addToCartIcon: 'text-gray-900'
      };
    }
    
    if (pkg.package_type === 'special_niche') {
      return {
        background: 'bg-gradient-to-br from-purple-500 to-pink-600',
        border: 'border-0',
        text: 'text-white',
        iconBg: 'bg-white/20',
        featureText: 'text-white',
        priceText: 'text-white',
        viewDetailsBtn: 'bg-white/10 text-white hover:bg-white/20 border border-white/30 flex-1',
        addToCartBtn: 'bg-white text-gray-900 hover:bg-gray-50 hover:scale-105',
        addToCartIcon: 'text-gray-900'
      };
    }
    
    return {
      background: 'bg-white',
      border: 'border border-gray-200',
      text: 'text-text-primary',
      iconBg: 'bg-blue-100',
      featureText: 'text-text-primary',
      priceText: 'text-text-primary',
      viewDetailsBtn: 'border-2 border-blue-600 text-blue-600 hover:bg-blue-50 flex-1',
      addToCartBtn: 'bg-linear-to-r from-blue-500 to-blue-600 text-white hover:from-blue-600 hover:to-blue-700',
      addToCartIcon: 'text-white'
    };
  };

  // Show initial loading skeleton
  if (loading && packages.length === 0) {
    return <PricingSectionSkeleton showToggle={showToggle} packageType={packageType} />;
  }

  // Show error state
  if (error && packages.length === 0) {
    return <PricingSectionError error={error} onRetry={handleRetry} />;
  }

  // Show empty state
  if (packages.length === 0 && !loading) {
    return <PricingSectionEmpty packageType={packageType} />;
  }

  return (
    <>
      <section id={id} className={`py-24 relative overflow-hidden ${className}`}>
        {/* Beautiful Background */}
        <div className="absolute inset-0 bg-linear-to-br from-blue-50 via-white to-purple-50">
          <div className="absolute top-0 left-0 w-72 h-72 bg-blue-200/20 rounded-full blur-3xl animate-float"></div>
          <div className="absolute bottom-0 right-0 w-96 h-96 bg-purple-200/20 rounded-full blur-3xl animate-float" style={{ animationDelay: '2s' }}></div>
          <div className="absolute top-1/2 left-1/3 w-64 h-64 bg-blue-100/30 rounded-full blur-3xl animate-float" style={{ animationDelay: '4s' }}></div>
          
          <div className="absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.8)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.8)_1px,transparent_1px)] bg-size-[64px_64px] mask-[radical-gradient(ellipse_80%_50%_at_50%_50%,black,transparent)]"></div>
        </div>

        <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Section Header */}
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6 }}
            viewport={{ once: true }}
            className="text-center mb-12"
          >
            <h2 className="text-4xl md:text-5xl lg:text-6xl font-bold text-text-primary mb-6">
              {title.split('Growth Plan')[0]}
              <span className="text-gradient bg-linear-to-r from-[#0066FF] to-[#FF6B35] ml-4">
                Growth Plan
              </span>
            </h2>
            
            <p className="text-xl text-text-secondary max-w-3xl mx-auto leading-relaxed mb-8">
              {description} 
              <span className="font-semibold text-[#0066FF]"> Everything included</span>, 
              no surprises.
            </p>

            {/* Package Type Toggle */}
            {showToggle && (
              <div className="flex justify-center mb-8">
                <div className="bg-white rounded-2xl p-2 shadow-lg border border-gray-200">
                  <div className="flex space-x-2">
                    <button
                      onClick={() => setPackageType('standard')}
                      disabled={loading}
                      className={`px-6 py-3 rounded-xl font-semibold transition-all duration-300 ${
                        packageType === 'standard'
                          ? 'bg-linear-to-r from-[#0066FF] to-[#00D4FF] text-white shadow-lg'
                          : 'text-text-secondary hover:text-[#0066FF] disabled:opacity-50'
                      } ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                      Standard Packages
                    </button>
                    <button
                      onClick={() => setPackageType('special_niche')}
                      disabled={loading}
                      className={`px-6 py-3 rounded-xl font-semibold transition-all duration-300 ${
                        packageType === 'special_niche'
                          ? 'bg-linear-to-r from-[#FF6B35] to-[#FF8C42] text-white shadow-lg'
                          : 'text-text-secondary hover:text-[#FF6B35] disabled:opacity-50'
                      } ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                      Special Niches
                    </button>
                  </div>
                </div>
              </div>
            )}

            {showToggle && packageType === 'special_niche' && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="bg-linear-to-r from-purple-50 to-pink-50 border border-purple-200 rounded-2xl p-6 max-w-2xl mx-auto"
              >
                <div className="flex items-center justify-center gap-3 text-purple-800">
                  <Sparkles className="h-5 w-5" />
                  <p className="font-semibold">Premium specialized packages for high-value niches</p>
                </div>
              </motion.div>
            )}
          </motion.div>

          {/* Pricing Cards with toggle loading overlay */}
          {loading && packages.length > 0 ? (
            <PricingSectionToggleLoading 
              packageType={packageType}
              packages={packages}
              getCardStyles={getCardStyles}
              getIcon={getIcon}
            />
          ) : (
            <motion.div
              key={packageType}
              variants={stagger}
              initial="initial"
              whileInView="animate"
              viewport={{ once: true }}
              className="grid grid-cols-1 lg:grid-cols-3 gap-8 max-w-7xl mx-auto"
            >
              {packages.map((pkg) => {
                const styles = getCardStyles(pkg);
                const IconComponent = getIcon(pkg);
                const finalPrice = pkg.sale_price ? parseFloat(pkg.sale_price) : parseFloat(pkg.base_price);
                const originalPrice = pkg.sale_price ? parseFloat(pkg.base_price) : null;
                const savings = originalPrice ? originalPrice - finalPrice : 0;
                
                return (
                  <motion.div
                    key={pkg.id}
                    variants={fadeInUp}
                    whileHover={{ y: -5 }}
                    className={`relative rounded-3xl p-8 transition-all duration-300 shadow-xl hover:shadow-2xl ${styles.background} ${styles.border} ${
                      pkg.is_popular ? 'lg:scale-105 z-10' : ''
                    }`}
                  >
                    {pkg.is_popular && (
                      <motion.div 
                        initial={{ scale: 0, rotate: -180 }}
                        animate={{ scale: 1, rotate: 0 }}
                        transition={{ duration: 0.5, delay: 0.5 }}
                        className="absolute -top-4 left-1/2 transform -translate-x-1/2"
                      >
                        <div className="bg-linear-to-r from-yellow-400 to-orange-500 text-white px-6 py-2 rounded-full text-sm font-bold shadow-lg flex items-center gap-2">
                          <Star className="h-4 w-4 fill-current" />
                          Most Popular
                        </div>
                      </motion.div>
                    )}

                    {pkg.package_type === 'special_niche' && !pkg.is_popular && (
                      <motion.div 
                        initial={{ scale: 0 }}
                        animate={{ scale: 1 }}
                        transition={{ duration: 0.5, delay: 0.3 }}
                        className="absolute -top-4 left-1/2 transform -translate-x-1/2"
                      >
                        <div className="bg-linear-to-r from-purple-500 to-pink-500 text-white px-6 py-2 rounded-full text-sm font-bold shadow-lg flex items-center gap-2">
                          <Sparkles className="h-4 w-4" />
                          Specialized
                        </div>
                      </motion.div>
                    )}

                    <div className="text-center mb-8">
                      <div className={`inline-flex items-center justify-center w-16 h-16 rounded-2xl mb-4 ${styles.iconBg}`}>
                        <IconComponent className={`h-7 w-7 ${
                          pkg.is_popular || pkg.package_type === 'special_niche' 
                            ? 'text-white' 
                            : 'text-blue-600'
                        }`} />
                      </div>
                      <h3 className={`text-2xl font-bold mb-3 ${styles.text}`}>
                        {pkg.name}
                      </h3>
                      <p className={`text-sm ${pkg.is_popular || pkg.package_type === 'special_niche' ? 'text-white/90' : 'text-text-secondary'}`}>
                        {pkg.description}
                      </p>
                    </div>

                    <div className="text-center mb-8">
                      <div className="flex items-center justify-center gap-3 mb-2">
                        <span className={`text-5xl font-bold ${styles.priceText}`}>
                          ${finalPrice.toLocaleString()}
                        </span>
                        {originalPrice && (
                          <span className={`text-lg line-through ${pkg.is_popular || pkg.package_type === 'special_niche' ? 'text-white/80' : 'text-text-secondary'}`}>
                            ${originalPrice.toLocaleString()}
                          </span>
                        )}
                      </div>
                      {savings > 0 && (
                        <div className={`text-sm font-semibold px-3 py-1 rounded-full inline-block ${
                          pkg.is_popular || pkg.package_type === 'special_niche'
                            ? 'bg-white/20 text-white' 
                            : 'bg-green-100 text-green-600'
                        }`}>
                          Save ${savings.toLocaleString()}
                        </div>
                      )}
                    </div>

                    <ul className="space-y-4 mb-8">
                      {pkg.features.map((feature, featureIndex) => (
                        <motion.li 
                          key={featureIndex}
                          initial={{ opacity: 0, x: -20 }}
                          whileInView={{ opacity: 1, x: 0 }}
                          transition={{ duration: 0.5, delay: 0.1 * featureIndex }}
                          viewport={{ once: true }}
                          className="flex items-start gap-3"
                        >
                          <Check className={`h-5 w-5 shrink-0 mt-0.5 ${
                            pkg.is_popular || pkg.package_type === 'special_niche'
                              ? 'text-white' 
                              : 'text-blue-500'
                          }`} />
                          <span className={`text-sm leading-relaxed ${styles.featureText}`}>
                            {feature}
                          </span>
                        </motion.li>
                      ))}
                    </ul>

                    {/* Two Buttons in One Line */}
                    <div className="flex gap-3">
                      {/* View Details Button - Large */}
                      <Link href={`/package/${pkg.slug}`} className="flex-1">
                        <motion.button
                          whileHover={{ scale: 1.02 }}
                          whileTap={{ scale: 0.98 }}
                          className={`w-full py-4 px-4 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-2 ${styles.viewDetailsBtn}`}
                        >
                          <Eye className="h-5 w-5" />
                          View Details
                        </motion.button>
                      </Link>
                      
                      {/* Add to Cart Button - Icon Only */}
                      <motion.button
                        whileHover={{ scale: 1.05 }}
                        whileTap={{ scale: 0.95 }}
                        onClick={() => handleAddToCart(pkg)}
                        disabled={isAddingToCart === pkg.id}
                        className={`w-14 h-14 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center ${styles.addToCartBtn} ${
                          isAddingToCart === pkg.id ? 'opacity-75 cursor-not-allowed' : ''
                        }`}
                        title="Add to Cart"
                      >
                        {isAddingToCart === pkg.id ? (
                          <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                        ) : (
                          <ShoppingCart className={`h-5 w-5 ${styles.addToCartIcon}`} />
                        )}
                      </motion.button>
                    </div>
                  </motion.div>
                );
              })}
            </motion.div>
          )}

          {/* Bottom CTA */}
          {showCustomPlanCTA && (
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              whileInView={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6, delay: 0.6 }}
              viewport={{ once: true }}
              className="text-center mt-16"
            >
              <p className="text-text-secondary mb-6">
                Need a custom package? We&apos;ve got you covered.
              </p>
              <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
                <button 
                  onClick={() => setIsCustomModalOpen(true)}
                  className="bg-linear-to-r from-gray-800 to-gray-900 text-white px-8 py-4 rounded-xl font-semibold hover:scale-105 transition-all duration-300 shadow-lg flex items-center gap-2"
                >
                  <Users className="h-5 w-5" />
                  Discuss Custom Needs
                  <ArrowRight className="h-4 w-4" />
                </button>
                
                <Link 
                  href="/packages"
                  className="bg-linear-to-r from-[#0066FF] to-[#00D4FF] text-white px-8 py-4 rounded-xl font-semibold hover:scale-105 transition-all duration-300 shadow-lg flex items-center gap-2"
                >
                  View All Packages
                  <ArrowRight className="h-4 w-4" />
                </Link>
              </div>
            </motion.div>
          )}
        </div>
      </section>

      {/* Custom Plan Modal */}
      <CustomPlanModal 
        isOpen={isCustomModalOpen} 
        onClose={() => setIsCustomModalOpen(false)} 
      />
    </>
  );
}