'use client';

import { useCart } from '@/hooks/useCart';
import { useWishlist } from '@/hooks/useWishlist';
import { motion } from 'framer-motion';
import { TrendingUp, Users, Globe, Shield, Heart, ShoppingCart, MessageCircle } from 'lucide-react';
import { useState, useEffect } from 'react';

interface Website {
  id: string;
  name: string;
  slug: string;
  domain: string;
  da: number;
  dr: number;
  traffic: string;
  spam_score: number;
  base_price: string;
  sale_price: string | null;
  content_service_price: string;
  niches: string[];
  description: string;
  featured_image: string | null;
  status: string;
  featured: boolean;
}

export default function PortfolioSection() {
  const [websites, setWebsites] = useState<Website[]>([]);
  const [loading, setLoading] = useState(true);

  const { addWebsite: addToCart } = useCart();
  const { addItem: addToWishlist, isInWishlist, removeItem: removeFromWishlist } = useWishlist();

  // Fetch websites from API
  useEffect(() => {
    const fetchWebsites = async () => {
      try {
        const response = await fetch('/api/frontend/websites');
        const result = await response.json();
        
        if (result.success) {
          setWebsites(result.data);
        } else {
          // Fallback to dummy data
          setWebsites(getDummyWebsites());
        }
      } catch (error) {
        // Fallback to dummy data
        console.error('Failed to fetch websites:', error);
        setWebsites(getDummyWebsites());
      } finally {
        setLoading(false);
      }
    };

    fetchWebsites();
  }, []);

  // Add to cart functionality
  const handleAddToCart = (website: Website) => {
    addToCart({
      websiteId: website.id,
      name: website.name,
      domain: website.domain,
      price: parseFloat(website.sale_price || website.base_price),
      contentService: false, // You can make this dynamic
    });
  };

  // Toggle wishlist
  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,
      });
    }
  };

  // Get consultation
  const getConsultation = (website: Website) => {
    // Open consultation modal or redirect
    console.log('Get consultation for:', website.name);
    // You can implement modal logic here
  };

  // Dummy data fallback
  const getDummyWebsites = (): 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
    },
    // Add other dummy websites similarly...
  ];

  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 fadeInUp = {
    initial: { y: 60, opacity: 0 },
    animate: { y: 0, opacity: 1 },
  };

  const stagger = {
    animate: {
      transition: {
        staggerChildren: 0.1,
      },
    },
  };

  if (loading) {
    return (
      <section id="portfolio" className="py-24 bg-linear-to-br from-slate-50 via-white to-blue-50/30 relative overflow-hidden">
        <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center">
            <div className="animate-pulse text-lg text-gray-600">Loading websites...</div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id="portfolio" className="py-24 bg-linear-to-br from-slate-50 via-white to-blue-50/30 relative overflow-hidden">
      {/* 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"
        >
          <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" />
            Premium Publishing Network
          </div>
          
          <h2 className="text-4xl md:text-5xl lg:text-6xl font-bold text-gray-900 mb-6">
            Featured On
            <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">
            Get featured on authoritative websites trusted by millions of readers worldwide. 
            <span className="font-semibold text-blue-600"> Real impact, measurable results</span>.
          </p>
        </motion.div>

        {/* Portfolio Grid */}
        <motion.div
          variants={stagger}
          initial="initial"
          whileInView="animate"
          viewport={{ once: true }}
          className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8 mb-16"
        >
          {websites.map((site) => (
            <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 Right */}
              <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 */}
                <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>

                {/* Dual Action Buttons */}
                <div className="flex flex-col gap-3">
                  {/* Add to Cart Button */}
                  <button 
                    onClick={() => handleAddToCart(site)}
                    className="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 rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all duration-300 cursor-pointer"
                  >
                    <ShoppingCart className="h-4 w-4" />
                    <span>Add to Cart</span>
                    <span className="font-bold">
                      ${parseFloat(site.sale_price || site.base_price).toLocaleString()}
                    </span>
                  </button>

                  {/* Get Consultation Button */}
                  <button 
                    onClick={() => getConsultation(site)}
                    className="flex items-center justify-center gap-2 bg-gray-100 hover:bg-gray-200 text-gray-700 py-3 rounded-xl font-semibold border border-gray-200 hover:border-gray-300 transition-all duration-300 cursor-pointer"
                  >
                    <MessageCircle className="h-4 w-4" />
                    <span>Get Consultation</span>
                  </button>
                </div>
              </div>
            </motion.div>
          ))}
        </motion.div>

        {/* CTA Section */}
        <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">
              Ready to Boost Your Authority?
            </h3>
            <p className="text-blue-100 mb-6 max-w-2xl mx-auto">
              Join thousands of brands that have increased their visibility and credibility through our premium publishing network.
            </p>
            <button className="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">
              View All Websites
            </button>
          </div>
          
          <p className="text-gray-500 mt-6 text-sm">
            Trusted by 5,000+ businesses worldwide • 98% client satisfaction
          </p>
        </motion.div>
      </div>
    </section>
  );
}