// src/app/components/admin/blocks/PortfolioSection.tsx

'use client';

import { motion } from 'framer-motion';
import { TrendingUp, Users, Globe, Shield, Heart, ShoppingCart, MessageCircle, Eye } from 'lucide-react';
import { useState, useEffect, useCallback } from 'react';
import { PortfolioSectionProps, Website } from '@/lib/page-builder/types';
import { useCart } from '@/hooks/useCart';
import { useWishlist } from '@/hooks/useWishlist';
import PortfolioSectionSkeleton from './PortfolioSkeletons/PortfolioSectionSkeleton';
import PortfolioSectionToggleLoading from './PortfolioSkeletons/PortfolioSectionToggleLoading';
import PortfolioSectionError from './PortfolioSkeletons/PortfolioSectionError';
import PortfolioSectionEmpty from './PortfolioSkeletons/PortfolioSectionEmpty';
import Link from 'next/link';

// Default mock data
const getDefaultWebsites = (): Website[] => [
  {
    id: 'web-1',
    name: 'TechCrunch',
    slug: 'techcrunch-guest-post',
    domain: 'techcrunch.com',
    da: 92,
    dr: 92,
    traffic: '50M',
    spam_score: 2,
    base_price: '899.00',
    sale_price: null,
    content_service_price: '30.00',
    niches: ['technology', 'startups', 'ai', 'gadgets'],
    description: 'Premium tech news and reviews covering startups, gadgets, and internet culture.',
    featured_image: null,
    status: 'active',
    featured: true
  },
  {
    id: 'web-2',
    name: 'Forbes',
    slug: 'forbes-guest-post',
    domain: 'forbes.com',
    da: 94,
    dr: 94,
    traffic: '85M',
    spam_score: 1,
    base_price: '1299.00',
    sale_price: '999.00',
    content_service_price: '50.00',
    niches: ['business', 'finance', 'entrepreneurship', 'leadership'],
    description: 'Global media company focused on business, investing, technology, entrepreneurship, leadership, and lifestyle.',
    featured_image: null,
    status: 'active',
    featured: true
  },
  {
    id: 'web-3',
    name: 'HubSpot',
    slug: 'hubspot-guest-post',
    domain: 'hubspot.com',
    da: 88,
    dr: 88,
    traffic: '25M',
    spam_score: 3,
    base_price: '699.00',
    sale_price: null,
    content_service_price: '25.00',
    niches: ['marketing', 'sales', 'crm', 'inbound'],
    description: 'Inbound marketing, sales, and service software platform.',
    featured_image: null,
    status: 'active',
    featured: true
  },
  {
    id: 'web-4',
    name: 'Mashable',
    slug: 'mashable-guest-post',
    domain: 'mashable.com',
    da: 86,
    dr: 86,
    traffic: '15M',
    spam_score: 4,
    base_price: '599.00',
    sale_price: '499.00',
    content_service_price: '20.00',
    niches: ['technology', 'entertainment', 'social media', 'gaming'],
    description: 'Digital media platform covering tech, culture, and entertainment.',
    featured_image: null,
    status: 'active',
    featured: true
  }
];

// Hook to fetch websites
function useWebsites(props: PortfolioSectionProps) {
  const [websites, setWebsites] = useState<Website[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [retryCount, setRetryCount] = useState(0);

  // Memoize fetchWebsites with useCallback to prevent unnecessary re-renders
  const fetchWebsites = useCallback(async () => {
    setWebsites([]);
    setLoading(true);
    setError(null);
    
    try {
      if (props.websites && props.websites.length > 0) {
        await new Promise(resolve => setTimeout(resolve, 500));
        setWebsites(props.websites);
        setLoading(false);
        return;
      }

      if (props.source === 'mock' && props.mockWebsites) {
        await new Promise(resolve => setTimeout(resolve, 800));
        setWebsites(props.mockWebsites);
        setLoading(false);
        return;
      }

      if (props.source === 'api') {
        const endpoint = props.apiEndpoint || '/api/frontend/websites';
        const response = await fetch(endpoint);
        
        if (!response.ok) {
          throw new Error(`Failed to fetch websites: ${response.status}`);
        }
        
        const result = await response.json();
        const websitesData = result.success ? result.data : result;
        
        if (Array.isArray(websitesData) && websitesData.length > 0) {
          setWebsites(websitesData);
        } else {
          setWebsites(getDefaultWebsites());
        }
        setLoading(false);
        return;
      }

      await new Promise(resolve => setTimeout(resolve, 600));
      setWebsites(getDefaultWebsites());
      setLoading(false);
      
    } catch (err) {
      console.error('Failed to load websites:', err);
      setError(err instanceof Error ? err.message : 'Failed to load websites');
      setWebsites(getDefaultWebsites());
      setLoading(false);
    }
  }, [props.websites, props.source, props.apiEndpoint, props.mockWebsites]);

  useEffect(() => {
    fetchWebsites();
  }, [fetchWebsites, retryCount]);

  const handleRetry = () => {
    setRetryCount(prev => prev + 1);
  };

  return { websites, loading, error, handleRetry };
}

export default function PortfolioSection(props: PortfolioSectionProps) {
  const {
    id,
    className = '',
    title = 'Featured On',
    description = 'Get featured on authoritative websites trusted by millions of readers worldwide.',
    badgeText = 'Premium Publishing Network',
    showBadge = true,
    columns = 4,
    showViewAllButton = true,
    viewAllButtonText = 'View All Websites',
    viewAllButtonLink = '/websites',
    showBottomCTA = true,
    bottomCTATitle = 'Ready to Boost Your Authority?',
    bottomCTADescription = 'Join thousands of brands that have increased their visibility and credibility through our premium publishing network.',
    bottomCTAButtonText = 'View All Websites',
    bottomCTAButtonLink = '/websites',
    trustText = 'Trusted by 5,000+ businesses worldwide • 98% client satisfaction',
  } = props;

  const { websites, loading, error, handleRetry } = useWebsites(props);
  const { addWebsite: addToCart } = useCart();
  const { addItem: addToWishlist, isInWishlist, removeItem: removeFromWishlist } = useWishlist();

  const getGridClass = () => {
    switch (columns) {
      case 2:
        return 'grid grid-cols-1 md:grid-cols-2 gap-8';
      case 3:
        return 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8';
      case 4:
        return 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8';
      default:
        return 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8';
    }
  };

  const getTrafficColor = (traffic: string) => {
    if (traffic.includes('80M') || traffic.includes('85M')) return 'text-red-500';
    if (traffic.includes('50M') || traffic.includes('70M')) return 'text-orange-500';
    if (traffic.includes('25M') || traffic.includes('15M')) return 'text-blue-500';
    return 'text-green-500';
  };

  const getDAColor = (da: number) => {
    if (da >= 90) return 'text-green-500';
    if (da >= 80) return 'text-blue-500';
    if (da >= 70) return 'text-yellow-500';
    return 'text-red-500';
  };

  const getSSColor = (ss: number) => {
    if (ss <= 2) return 'text-green-500';
    if (ss <= 4) return 'text-yellow-500';
    return 'text-red-500';
  };

  const handleAddToCart = (website: Website) => {
    addToCart({
      type: 'website',
      websiteId: website.id,
      name: website.name,
      domain: website.domain,
      price: parseFloat(website.sale_price || website.base_price),
      contentService: false,
    });
  };

  const handleToggleWishlist = (website: Website) => {
    if (isInWishlist(website.id)) {
      removeFromWishlist(website.id);
    } else {
      addToWishlist({
        websiteId: website.id,
        name: website.name,
        domain: website.domain,
        price: parseFloat(website.sale_price || website.base_price),
        da: website.da,
        dr: website.dr,
        niches: website.niches,
      });
    }
  };

  const fadeInUp = {
    initial: { y: 60, opacity: 0 },
    animate: { y: 0, opacity: 1 },
  };

  const stagger = {
    animate: {
      transition: {
        staggerChildren: 0.1,
      },
    },
  };

  // Show initial loading skeleton
  if (loading && websites.length === 0) {
    return <PortfolioSectionSkeleton columns={columns} />;
  }

  // Show error state
  if (error && websites.length === 0) {
    return <PortfolioSectionError error={error} onRetry={handleRetry} />;
  }

  // Show empty state
  if (websites.length === 0 && !loading) {
    return <PortfolioSectionEmpty />;
  }

  return (
    <section id={id} className={`py-24 bg-linear-to-br from-slate-50 via-white to-blue-50/30 relative overflow-hidden ${className}`}>
      {/* Background Elements */}
      <div className="absolute top-10 right-10 w-72 h-72 bg-blue-200/10 rounded-full blur-3xl"></div>
      <div className="absolute bottom-10 left-10 w-96 h-96 bg-purple-200/10 rounded-full blur-3xl"></div>
      <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-cyan-200/5 rounded-full blur-3xl"></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-20"
        >
          {showBadge && (
            <div className="inline-flex items-center gap-2 bg-blue-50 text-blue-700 px-4 py-2 rounded-full text-sm font-medium mb-6">
              <TrendingUp className="h-4 w-4" />
              {badgeText}
            </div>
          )}
          
          <h2 className="text-4xl md:text-5xl lg:text-6xl font-bold text-gray-900 mb-6">
            {title}
            <span className="text-gradient bg-linear-to-r from-[#0066FF] to-[#FF6B35] ml-2">
              Top-Tier Media
            </span>
          </h2>
          
          <p className="text-xl text-gray-600 max-w-3xl mx-auto leading-relaxed">
            {description}
            <span className="font-semibold text-blue-600"> Real impact, measurable results</span>.
          </p>
        </motion.div>

        {/* Portfolio Grid with toggle loading overlay */}
        {loading && websites.length > 0 ? (
          <PortfolioSectionToggleLoading websites={websites} columns={columns} />
        ) : (
          <motion.div
            variants={stagger}
            initial="initial"
            whileInView="animate"
            viewport={{ once: true }}
            className={`${getGridClass()} mb-16`}
          >
            {websites.map((site) => {
              const finalPrice = parseFloat(site.sale_price || site.base_price);
              const originalPrice = site.sale_price ? parseFloat(site.base_price) : null;
              
              return (
                <motion.div
                  key={site.id}
                  variants={fadeInUp}
                  whileHover={{ 
                    y: -8,
                    scale: 1.02,
                    transition: { duration: 0.3 }
                  }}
                  className="group bg-white rounded-3xl shadow-xl hover:shadow-2xl transition-all duration-500 overflow-hidden border border-gray-100 relative"
                >
                  {/* Heart Icon - Top Left */}
                  <button
                    onClick={() => handleToggleWishlist(site)}
                    className="absolute top-4 left-4 z-20 bg-white/90 hover:bg-white rounded-full p-2 transition-all duration-300 shadow-lg"
                  >
                    <Heart 
                      className={`h-5 w-5 ${
                        isInWishlist(site.id) 
                          ? 'fill-red-500 text-red-500' 
                          : 'text-gray-400 hover:text-red-500'
                      } transition-colors`}
                    />
                  </button>

                  {/* Header with Gradient */}
                  <div className="relative h-32 bg-linear-to-br from-slate-900 via-blue-900 to-purple-900 overflow-hidden">
                    <div className="absolute inset-0 bg-linear-to-br from-blue-600/20 to-purple-600/20 group-hover:scale-110 transition-transform duration-700"></div>
                    
                    <div className="absolute inset-0 flex items-center justify-center p-6">
                      <div className="text-white text-center">
                        <div className="w-12 h-12 bg-white/10 rounded-xl backdrop-blur-sm flex items-center justify-center mx-auto mb-2 group-hover:scale-110 transition-transform duration-300">
                          <Globe className="h-6 w-6" />
                        </div>
                        <div className="text-lg font-bold">{site.name}</div>
                        <div className="text-blue-200 text-xs mt-1">{site.domain}</div>
                      </div>
                    </div>
                    
                    {/* Category Badge */}
                    {site.niches && site.niches.length > 0 && (
                      <div className="absolute top-3 right-3 bg-white/20 text-white px-3 py-1 rounded-full text-xs font-semibold backdrop-blur-sm">
                        {site.niches[0]}
                      </div>
                    )}
                  </div>

                  {/* Content */}
                  <div className="p-6">
                    {/* Stats Grid */}
                    <div className="grid grid-cols-2 gap-4 mb-6">
                      <div className="text-center p-3 bg-gray-50 rounded-2xl group-hover:bg-blue-50 transition-colors">
                        <Users className="h-5 w-5 text-blue-600 mx-auto mb-2" />
                        <div className={`text-lg font-bold ${getTrafficColor(site.traffic)}`}>
                          {site.traffic}
                        </div>
                        <div className="text-xs text-gray-500">Visitors</div>
                      </div>
                      
                      <div className="text-center p-3 bg-gray-50 rounded-2xl group-hover:bg-orange-50 transition-colors">
                        <TrendingUp className="h-5 w-5 text-orange-600 mx-auto mb-2" />
                        <div className="text-lg font-bold text-orange-600">
                          DR {site.dr}
                        </div>
                        <div className="text-xs text-gray-500">Rating</div>
                      </div>

                      <div className="text-center p-3 bg-gray-50 rounded-2xl group-hover:bg-purple-50 transition-colors">
                        <TrendingUp className="h-5 w-5 text-purple-600 mx-auto mb-2" />
                        <div className={`text-lg font-bold ${getDAColor(site.da)}`}>
                          DA {site.da}
                        </div>
                        <div className="text-xs text-gray-500">Authority</div>
                      </div>
                      
                      <div className="text-center p-3 bg-gray-50 rounded-2xl group-hover:bg-red-50 transition-colors">
                        <Shield className="h-5 w-5 text-red-600 mx-auto mb-2" />
                        <div className={`text-lg font-bold ${getSSColor(site.spam_score)}`}>
                          SS {site.spam_score}
                        </div>
                        <div className="text-xs text-gray-500">Spam Score</div>
                      </div>
                    </div>

                    {/* Price Display */}
                    <div className="mb-4 text-center">
                      <div className="flex items-center justify-center gap-3">
                        <span className="text-2xl font-bold text-blue-600">
                          ${finalPrice.toLocaleString()}
                        </span>
                        {originalPrice && (
                          <span className="text-sm line-through text-gray-400">
                            ${originalPrice.toLocaleString()}
                          </span>
                        )}
                      </div>
                      {originalPrice && (
                        <div className="text-xs text-green-600 font-semibold mt-1">
                          Save ${(originalPrice - finalPrice).toLocaleString()}
                        </div>
                      )}
                    </div>

                    {/* Two Buttons in One Line */}
                    <div className="flex gap-3">
                      {/* Add to Cart Button - Large */}
                      <button 
                        onClick={() => handleAddToCart(site)}
                        className="flex-1 flex items-center justify-center gap-2 bg-linear-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white py-3 px-4 rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all duration-300 cursor-pointer group/btn"
                      >
                        <ShoppingCart className="h-4 w-4 group-hover/btn:scale-110 transition-transform" />
                        <span>Add to Cart</span>
                      </button>

                      {/* View Details Button - Icon Only */}
                      <Link href={`/website/${site.slug}`}>
                        <button 
                          className="w-12 h-12 flex items-center justify-center bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl font-semibold border border-gray-200 hover:border-gray-300 transition-all duration-300 cursor-pointer group/icon"
                          title="View Details"
                        >
                          <Eye className="h-5 w-5 group-hover/icon:scale-110 transition-transform" />
                        </button>
                      </Link>
                    </div>
                  </div>
                </motion.div>
              );
            })}
          </motion.div>
        )}

        {/* View All Button */}
        {showViewAllButton && (
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.4 }}
            viewport={{ once: true }}
            className="text-center mb-16"
          >
            <Link 
              href={viewAllButtonLink}
              className="inline-block bg-linear-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white px-8 py-4 rounded-2xl font-semibold hover:scale-105 transition-all duration-300 shadow-lg"
            >
              {viewAllButtonText}
            </Link>
          </motion.div>
        )}

        {/* Bottom CTA Section */}
        {showBottomCTA && (
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.8 }}
            viewport={{ once: true }}
            className="text-center"
          >
            <div className="bg-linear-to-r from-blue-600 to-cyan-600 rounded-3xl p-8 text-white shadow-2xl">
              <h3 className="text-2xl md:text-3xl font-bold mb-4">
                {bottomCTATitle}
              </h3>
              <p className="text-blue-100 mb-6 max-w-2xl mx-auto">
                {bottomCTADescription}
              </p>
              <Link 
                href={bottomCTAButtonLink}
                className="inline-block bg-white text-blue-600 hover:bg-gray-100 px-8 py-4 rounded-2xl font-semibold hover:scale-105 transition-all duration-300 shadow-lg"
              >
                {bottomCTAButtonText}
              </Link>
            </div>
            
            {trustText && (
              <p className="text-gray-500 mt-6 text-sm">
                {trustText}
              </p>
            )}
          </motion.div>
        )}
      </div>
    </section>
  );
}