'use client';

import Link from 'next/link';
import { motion } from 'framer-motion';
import { Check, Star, Zap, Crown, Sparkles, Users, ArrowRight, TrendingUp, Globe } from 'lucide-react';
import { useCart } from '@/hooks/useCart';

interface Website {
  id: string;
  name: string;
  slug: string;
  domain: string;
  da: number;
  dr: number;
  traffic: string;
  spam_score: number;
  backlinks: number;
  link_type: string;
  base_price: number;
  sale_price: number | null;
  featured_image: string | null;
  status: string;
}

interface Package {
  id: string;
  name: string;
  slug: string;
  description: string;
  package_type: 'standard' | 'special_niche' | 'custom';
  base_price: number;
  sale_price: number | null;
  features: string[];
  is_popular: boolean;
  is_featured: boolean;
  meta_title: string | null;
  meta_description: string | null;
  schemas: unknown[];
  websites: Website[];
  created_at: string;
  updated_at: string;
}

interface PackageCardProps {
  package: Package;
  showWebsites?: boolean;
  onSelect?: (pkg: Package) => void;
}

export default function PackageCard({ package: pkg, showWebsites = false, onSelect }: PackageCardProps) {
  const { addPackage } = useCart();

  // Helper function to format price with 2 decimal places
  const formatPrice = (price: number | string | null) => {
    if (price === null || price === undefined) return '0.00';
    const numPrice = typeof price === 'string' ? parseFloat(price) : price;
    if (isNaN(numPrice)) return '0.00';
    return numPrice.toFixed(2);
  };

  // Helper function to calculate savings
  const calculateSavings = (originalPrice: number, salePrice: number) => {
    const savings = originalPrice - salePrice;
    return formatPrice(savings);
  };

  const displayPrice = pkg.sale_price && pkg.sale_price < pkg.base_price ? pkg.sale_price : pkg.base_price;
  const originalPrice = pkg.sale_price ? pkg.base_price : null;
  const hasDiscount = pkg.sale_price && pkg.sale_price < pkg.base_price;
  const savings = hasDiscount ? calculateSavings(pkg.base_price, pkg.sale_price as number) : null;

  // Get unique websites for this package
  const uniqueWebsites = pkg.websites.filter((website, index, self) => 
    index === self.findIndex(w => w.id === website.id)
  );

  // Get icon component name instead of component
  const getIconName = () => {
    if (pkg.package_type === 'special_niche') return 'sparkles';
    if (pkg.is_popular) return 'star';
    if (pkg.name.toLowerCase().includes('agency')) return 'users';
    if (pkg.name.toLowerCase().includes('enterprise')) return 'crown';
    return 'zap';
  };

  // Get icon as component inline
  const renderIcon = () => {
    const iconName = getIconName();
    const iconProps = { className: `h-7 w-7 ${pkg.is_popular || pkg.package_type === 'special_niche' ? 'text-white' : 'text-blue-600'}` };
    
    switch(iconName) {
      case 'sparkles': return <Sparkles {...iconProps} />;
      case 'star': return <Star {...iconProps} />;
      case 'users': return <Users {...iconProps} />;
      case 'crown': return <Crown {...iconProps} />;
      default: return <Zap {...iconProps} />;
    }
  };

  const getCtaText = () => {
    if (pkg.package_type === 'special_niche') return 'Add to Cart';
    if (pkg.is_popular) return 'Add to Cart';
    if (pkg.name.toLowerCase().includes('starter')) return 'Add to Cart';
    if (pkg.name.toLowerCase().includes('agency')) return 'Add to Cart';
    return 'Add to Cart';
  };

  const getCardStyles = () => {
    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'
      };
    }
    
    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'
      };
    }
    
    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'
    };
  };

  const getButtonStyles = () => {
    if (pkg.is_popular || pkg.package_type === 'special_niche') {
      return 'bg-white text-gray-900 hover:bg-gray-50 hover:scale-105 shadow-lg font-bold';
    }
    return 'bg-linear-to-r from-blue-500 to-blue-600 text-white hover:from-blue-600 hover:to-blue-700 hover:scale-105 shadow-lg';
  };

  const styles = getCardStyles();
  const ctaText = getCtaText();

  const handleAddToCart = () => {
    // Add package to cart
    if (pkg.websites && pkg.websites.length > 0) {
      // Add as package
      addPackage({
        packageId: pkg.id,
        packageSlug: pkg.slug,
        name: pkg.name,
        description: pkg.description,
        packageType: pkg.package_type,
        features: pkg.features,
        price: typeof displayPrice === 'number' ? displayPrice : parseFloat(displayPrice),
        contentService: false,
        assignedWebsiteIds: pkg.websites.map(w => w.id),
      });
    }
  };

  const handleSelect = () => {
    if (onSelect) {
      onSelect(pkg);
    } else {
      handleAddToCart();
    }
  };

  return (
    <motion.div
      whileHover={{ y: -5 }}
      className={`relative rounded-3xl p-8 transition-all duration-300 shadow-xl hover:shadow-2xl ${styles.background} ${styles.border}`}
    >
      {/* Popular Badge */}
      {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>
      )}

      {/* Special Niche Badge */}
      {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>
      )}

      {/* Featured Badge */}
      {pkg.is_featured && !pkg.is_popular && pkg.package_type !== 'special_niche' && (
        <div className="absolute top-4 right-4">
          <div className="bg-linear-to-r from-amber-500 to-orange-500 text-white px-3 py-1 rounded-full text-xs font-semibold flex items-center gap-1">
            <Star className="h-3 w-3" />
            Featured
          </div>
        </div>
      )}

      {/* Package Header */}
      <div className="text-center mb-8">
        <div className={`inline-flex items-center justify-center w-16 h-16 rounded-2xl mb-4 ${styles.iconBg}`}>
          {renderIcon()}
        </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>

      {/* Package Type Badge */}
      <div className="flex justify-center mb-4">
        <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${
          pkg.package_type === 'special_niche' 
            ? 'bg-white/20 text-white' 
            : 'bg-gray-100 text-gray-800'
        }`}>
          {pkg.package_type === 'standard' && 'Standard Package'}
          {pkg.package_type === 'special_niche' && 'Special Niche'}
          {pkg.package_type === 'custom' && 'Custom Package'}
        </span>
      </div>

      {/* Pricing */}
      <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}`}>
            ${formatPrice(displayPrice)}
          </span>
          {originalPrice && (
            <span className={`text-lg line-through ${pkg.is_popular || pkg.package_type === 'special_niche' ? 'text-white/80' : 'text-text-secondary'}`}>
              ${formatPrice(originalPrice)}
            </span>
          )}
        </div>
        {hasDiscount && (
          <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}
          </div>
        )}
      </div>

      {/* Features */}
      <ul className="space-y-4 mb-8">
        {pkg.features.slice(0, 8).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>
        ))}
        {pkg.features.length > 8 && (
          <li className={`text-sm pl-8 ${styles.featureText}`}>
            +{pkg.features.length - 8} more features
          </li>
        )}
      </ul>

      {/* Websites Preview */}
      {showWebsites && uniqueWebsites.length > 0 && (
        <div className={`mb-6 p-3 rounded-xl ${
          pkg.is_popular || pkg.package_type === 'special_niche' 
            ? 'bg-white/10' 
            : 'bg-slate-50'
        }`}>
          <p className={`text-xs font-medium mb-2 ${
            pkg.is_popular || pkg.package_type === 'special_niche' 
              ? 'text-white/80' 
              : 'text-slate-500'
          }`}>
            Included Websites ({uniqueWebsites.length}):
          </p>
          <div className="flex flex-wrap gap-2">
            {uniqueWebsites.slice(0, 3).map((website) => (
              <span key={website.id} className={`inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium ${
                pkg.is_popular || pkg.package_type === 'special_niche'
                  ? 'bg-white/20 text-white'
                  : 'bg-blue-50 text-blue-700'
              }`}>
                <Globe className="h-3 w-3" />
                {website.name}
              </span>
            ))}
            {uniqueWebsites.length > 3 && (
              <span className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${
                pkg.is_popular || pkg.package_type === 'special_niche'
                  ? 'bg-white/20 text-white/80'
                  : 'bg-gray-100 text-gray-600'
              }`}>
                +{uniqueWebsites.length - 3} more
              </span>
            )}
          </div>
          
          {/* Quick Metrics */}
          {uniqueWebsites.length > 0 && (
            <div className="flex items-center justify-between mt-3 pt-2 text-xs">
              <div className="flex items-center gap-1">
                <TrendingUp className={`h-3 w-3 ${
                  pkg.is_popular || pkg.package_type === 'special_niche' 
                    ? 'text-white/70' 
                    : 'text-blue-600'
                }`} />
                <span className={pkg.is_popular || pkg.package_type === 'special_niche' ? 'text-white/70' : 'text-slate-600'}>
                  DA {uniqueWebsites[0].da}
                </span>
              </div>
              <div className="flex items-center gap-1">
                <Users className={`h-3 w-3 ${
                  pkg.is_popular || pkg.package_type === 'special_niche' 
                    ? 'text-white/70' 
                    : 'text-orange-600'
                }`} />
                <span className={pkg.is_popular || pkg.package_type === 'special_niche' ? 'text-white/70' : 'text-slate-600'}>
                  DR {uniqueWebsites[0].dr}
                </span>
              </div>
              <div className="flex items-center gap-1">
                <Globe className={`h-3 w-3 ${
                  pkg.is_popular || pkg.package_type === 'special_niche' 
                    ? 'text-white/70' 
                    : 'text-green-600'
                }`} />
                <span className={pkg.is_popular || pkg.package_type === 'special_niche' ? 'text-white/70' : 'text-slate-600'}>
                  {uniqueWebsites[0].traffic}
                </span>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Action Buttons */}
      <div className="flex gap-3">
        <motion.button
          whileHover={{ scale: 1.02 }}
          whileTap={{ scale: 0.98 }}
          onClick={handleSelect}
          className={`flex-1 py-4 px-6 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-2 ${getButtonStyles()}`}
        >
          {ctaText}
          <ArrowRight className="h-4 w-4" />
        </motion.button>
        
        <Link
          href={`/package/${pkg.slug}`}
          className={`py-4 px-6 rounded-xl font-semibold transition-all duration-300 flex items-center justify-center gap-2 ${
            pkg.is_popular || pkg.package_type === 'special_niche'
              ? 'bg-white/20 text-white hover:bg-white/30'
              : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
          }`}
        >
          Details
        </Link>
      </div>
    </motion.div>
  );
}