import { useState, useEffect } from "react"
import { useParams, Link } from "react-router"
import { useCart } from "@/context/CartContext"
import { Star, ShoppingCart, CheckCircle2, Clock, Eye, TrendingUp, ChevronDown, ChevronUp, ArrowLeft, MessageCircle, Send, Zap, Heart } from "lucide-react"
import { getProductBySlug, getRelatedProducts, getProductImage } from "@/data/staticData"
import { SEO } from "@/components/SEO"
import { SchemaMarkup } from "@/components/SchemaMarkup"
import { getProductSeo } from "@/data/productSeo"

export default function ProductDetail() {
  const { slug } = useParams<{ slug: string }>()
  const { addItem } = useCart()
  const [selectedPlan, setSelectedPlan] = useState("")
  const [openFaq, setOpenFaq] = useState<number | null>(0)
  const [inWishlist, setInWishlist] = useState(false)

  const product = slug ? getProductBySlug(slug) : undefined
  const related = product ? getRelatedProducts(product, 4) : []
  const seoData = slug ? getProductSeo(slug) : undefined

  // Track wishlist in localStorage
  useEffect(() => {
    if (product) {
      const wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]") as string[]
      setInWishlist(wishlist.includes(product.id))
    }
  }, [product?.id])

  const toggleWishlist = () => {
    if (!product) return
    const wishlist = JSON.parse(localStorage.getItem("wishlist") || "[]") as string[]
    const newWishlist = wishlist.includes(product.id)
      ? wishlist.filter(id => id !== product.id)
      : [...wishlist, product.id]
    localStorage.setItem("wishlist", JSON.stringify(newWishlist))
    setInWishlist(!inWishlist)
  }

  useEffect(() => { if (product?.plans?.length) setSelectedPlan(product.plans[0]) }, [product?.plans])

  if (!product) return <div className="min-h-screen pt-28 px-4 flex items-center justify-center"><div className="text-center"><p className="text-xl text-slate-400 mb-4">Product not found</p><Link to="/shop" className="btn-primary">Browse Products</Link></div></div>

  const price = product.price, original = product.originalPrice, discount = Math.round(((original - price) / original) * 100)

  const seoTitle = product.seoTitle || `Buy ${product.name} | Cheap ${product.category} Subscription`
  const seoDesc = product.seoDescription || `Buy ${product.name} cheap at $${product.price} — ${discount}% off. Genuine license. Instant delivery. 24H money-back guarantee.`
  const seoKeywords = product.keywords?.join(", ") || `buy ${product.name}, ${product.category} subscription, cheap ${product.category}, ${product.name} discount`
  const plans = (product.plans || []) as string[]
  const features = (product.features || []) as string[]
  const benefits = (product.benefits || []) as string[]
  const reviews = (product.reviews || []) as Array<{ name: string; location: string; text: string; rating: number }>
  const faqs = (product.faqs || []) as Array<{ q: string; a: string }>
  const img = getProductImage(product.slug, product.category)

  const hasFeatures = features.length > 0
  const hasBenefits = benefits.length > 0
  const hasReviews = reviews.length > 0
  const hasFaqs = faqs.length > 0
  const hasRelated = related.length > 0

  return (
    <>
      <SEO
        title={seoData?.metaTitle || seoTitle}
        description={seoData?.metaDescription || seoDesc}
        keywords={seoData?.semanticKeywords.slice(0, 8).join(", ") || seoKeywords}
        image={img}
        imageAlt={`Buy ${product.name} - ${product.category} subscription at ${discount}% off`}
        path={`/product/${product.slug}`}
        type="product"
      />
      <SchemaMarkup type="Product" data={product} />
    <div className="min-h-screen pt-28 pb-16 px-4">
      <div className="max-w-7xl mx-auto">
        <Link to="/shop" className="flex items-center gap-2 text-sm text-slate-400 hover:text-white mb-6 transition-colors"><ArrowLeft className="w-4 h-4" />Back to Shop</Link>
        
        {/* Product Hero */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-10 mb-16">
          <div className="glass-card overflow-hidden relative">
            <img src={img} alt={product.name} className="w-full h-full object-cover min-h-[400px]" />
            {product.badge && <div className="absolute top-4 left-4 px-4 py-2 rounded-full bg-[#f97316] text-sm font-bold">{product.badge}</div>}
            <div className="absolute top-4 right-4 px-3 py-2 rounded-full bg-red-500 font-bold">{discount}% OFF</div>
            <div className="absolute bottom-4 left-4 flex items-center gap-2 px-3 py-2 rounded-full bg-black/60 backdrop-blur-sm text-sm">
              <Eye className="w-4 h-4 text-[#f97316]" />
              <span className="text-[#f97316] font-bold">{Math.floor(Math.random() * 40) + 8}</span>
              <span className="text-slate-400">viewing</span>
            </div>
          </div>
          <div>
            <div className="flex items-center gap-2 mb-3">
              {[1,2,3,4,5].map(s => <Star key={s} className="w-4 h-4 fill-[#f97316] text-[#f97316]" />)}
              <span className="text-sm text-slate-400">({reviews.length} reviews)</span>
            </div>
            <h1 className="text-3xl md:text-4xl font-bold mb-3">{product.name}</h1>
            <p className="text-slate-400 mb-6">{product.shortDescription}</p>
            <div className="flex items-center gap-4 mb-6 flex-wrap">
              <div className="flex items-center gap-2 px-3 py-2 rounded-full bg-[#f97316]/10 text-sm">
                <TrendingUp className="w-4 h-4 text-[#f97316]" />
                <span className="text-[#f97316] font-bold">{Math.floor(Math.random() * 200) + 50}</span>
                <span className="text-slate-400">sold this week</span>
              </div>
              <div className="px-3 py-2 rounded-full bg-green-500/10 text-sm text-green-400 font-medium">Trending</div>
            </div>
            <div className="flex items-baseline gap-3 mb-6">
              <span className="text-4xl font-bold text-[#f97316]">${product.price}</span>
              <span className="text-xl text-slate-500 line-through">${product.originalPrice}</span>
              <span className="px-3 py-1 rounded-full bg-green-500/20 text-green-400 text-sm font-bold">Save {discount}%</span>
            </div>
            {plans.length > 0 && (
              <div className="mb-6">
                <label className="text-sm text-slate-400 mb-2 block">Select Plan:</label>
                <div className="flex flex-wrap gap-2">
                  {plans.map(plan => (
                    <button key={plan} onClick={() => setSelectedPlan(plan)} className={`px-4 py-2 rounded-xl text-sm transition-all ${selectedPlan === plan ? "bg-[#f97316] text-white" : "bg-white/5 border border-white/10 hover:border-[#f97316]/50"}`}>{plan}</button>
                  ))}
                </div>
              </div>
            )}
            <div className="space-y-2 mb-6 text-sm">
              {product.activation && <div className="flex items-center gap-2 text-slate-400"><Zap className="w-4 h-4 text-[#22c55e]" />Activation: {product.activation}</div>}
              {product.deliveryTime && <div className="flex items-center gap-2 text-slate-400"><Clock className="w-4 h-4 text-[#22c55e]" />Delivery: {product.deliveryTime}</div>}
            </div>
            <div className="space-y-3">
              <button onClick={() => addItem(product.id)} className="btn-primary w-full flex items-center justify-center gap-2 text-lg py-4">
                <ShoppingCart className="w-5 h-5" />Add to Cart
              </button>
              <div className="grid grid-cols-2 gap-3">
                <a href="https://wa.me/917038146526" target="_blank" rel="noopener noreferrer nofollow" className="flex items-center justify-center gap-2 px-4 py-3 rounded-full bg-green-500/10 border border-green-500/30 text-green-400 hover:bg-green-500/20 transition-all text-sm">
                  <MessageCircle className="w-4 h-4" />WhatsApp
                </a>
                <a href="https://t.me/mfatool" target="_blank" rel="noopener noreferrer nofollow" className="flex items-center justify-center gap-2 px-4 py-3 rounded-full bg-blue-500/10 border border-blue-500/30 text-blue-400 hover:bg-blue-500/20 transition-all text-sm">
                  <Send className="w-4 h-4" />Telegram
                </a>
              </div>
              <button onClick={toggleWishlist} className={`w-full flex items-center justify-center gap-2 px-4 py-3 rounded-xl border text-sm transition-all ${inWishlist ? "border-red-500/30 bg-red-500/10 text-red-400" : "border-white/10 hover:border-white/20"}`}>
                <Heart className={`w-4 h-4 ${inWishlist ? "fill-red-400" : ""}`} />
                {inWishlist ? "In Wishlist" : "Add to Wishlist"}
              </button>
            </div>
            <div className="grid grid-cols-2 gap-3 mt-6">
              {["24H Money Back","Genuine License","Instant Delivery","99.8% Success"].map((t,i) => (
                <div key={i} className="flex items-center gap-2 text-sm text-slate-400"><CheckCircle2 className="w-4 h-4 text-[#22c55e]" />{t}</div>
              ))}
            </div>
          </div>
        </div>

        {/* Rich SEO Description */}
        {seoData && (
          <div className="mb-16">
            <div
              className="prose prose-invert prose-lg max-w-none blog-content"
              dangerouslySetInnerHTML={{ __html: seoData.longDescription }}
            />
          </div>
        )}

        {/* Why Choose Subscription Hero */}
        {seoData && (
          <div className="glass-card p-8 mb-16 bg-gradient-to-br from-[#f97316]/10 to-[#22c55e]/5 border border-[#f97316]/20">
            <h2 className="text-2xl font-bold mb-6 flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-[#f97316]/20 flex items-center justify-center">
                <Zap className="w-5 h-5 text-[#f97316]" />
              </div>
              Why Choose Subscription Hero?
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {seoData.whyChooseUs.map((item, i) => (
                <div key={i} className="flex items-start gap-3">
                  <CheckCircle2 className="w-5 h-5 text-[#22c55e] flex-shrink-0 mt-0.5" />
                  <span className="text-slate-300">{item}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Features & Benefits */}
        {(hasFeatures || hasBenefits || seoData) && (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-16">
            {(hasFeatures || seoData) && (
              <div className="glass-card p-6">
                <h2 className="text-xl font-bold mb-4 flex items-center gap-2"><CheckCircle2 className="w-5 h-5 text-[#22c55e]" />Key Features</h2>
                <ul className="space-y-3">
                  {(seoData?.features || features).map((f,i) => <li key={i} className="flex items-start gap-3"><span className="text-[#22c55e] mt-0.5">✓</span><span className="text-slate-300">{f}</span></li>)}
                </ul>
              </div>
            )}
            {(hasBenefits || seoData) && (
              <div className="glass-card p-6">
                <h2 className="text-xl font-bold mb-4 flex items-center gap-2"><Zap className="w-5 h-5 text-[#f97316]" />Key Benefits</h2>
                <ul className="space-y-3">
                  {(seoData?.benefits || benefits).map((b,i) => <li key={i} className="flex items-start gap-3"><span className="text-[#f97316] mt-0.5">✓</span><span className="text-slate-300">{b}</span></li>)}
                </ul>
              </div>
            )}
          </div>
        )}

        {/* Reviews */}
        {hasReviews && (
          <div className="mb-16">
            <h2 className="text-2xl font-bold mb-6">Customer Reviews</h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {reviews.slice(0,6).map((r,i) => (
                <div key={i} className="glass-card p-5">
                  <div className="flex items-center gap-1 mb-2">{[1,2,3,4,5].map(s => <Star key={s} className="w-3 h-3 fill-[#f97316] text-[#f97316]" />)}</div>
                  <p className="text-slate-300 text-sm mb-3">{r.text}</p>
                  <div className="flex items-center justify-between text-xs text-slate-500">
                    <span className="font-medium text-slate-400">{r.name}</span>
                    <span>{r.location}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* FAQs — Enhanced with SEO data */}
        {(hasFaqs || seoData) && (
          <div className="mb-16">
            <h2 className="text-2xl font-bold mb-6">Frequently Asked Questions</h2>
            <div className="space-y-3">
              {(seoData?.faqs || faqs).map((f,i) => (
                <div key={i} className="glass-card overflow-hidden">
                  <button onClick={() => setOpenFaq(openFaq === i ? null : i)} className="w-full flex items-center justify-between p-5 text-left">
                    <span className="font-medium pr-4">{f.q}</span>
                    {openFaq === i ? <ChevronUp className="w-5 h-5 text-slate-400 flex-shrink-0" /> : <ChevronDown className="w-5 h-5 text-slate-400 flex-shrink-0" />}
                  </button>
                  {openFaq === i && <div className="px-5 pb-5 text-slate-400 text-sm animate-fade-in">{f.a}</div>}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Featured Snippets — Quick Answers */}
        {seoData && seoData.featuredSnippets.length > 0 && (
          <div className="mb-16">
            <h2 className="text-2xl font-bold mb-6">Quick Answers</h2>
            <div className="space-y-4">
              {seoData.featuredSnippets.map((fs, i) => (
                <div key={i} className="glass-card p-5 border-l-4 border-l-[#22c55e]">
                  <h3 className="font-semibold mb-2 text-white">{fs.q}</h3>
                  <p className="text-slate-400 text-sm">{fs.a}</p>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Internal Links */}
        {seoData && seoData.internalLinks.length > 0 && (
          <div className="mb-16">
            <h2 className="text-2xl font-bold mb-6">Explore More</h2>
            <div className="flex flex-wrap gap-3">
              {seoData.internalLinks.map((link, i) => (
                <Link key={i} to={link.to} className="px-4 py-2 rounded-full bg-white/5 border border-white/10 hover:border-[#f97316]/50 hover:text-[#f97316] transition-all text-sm">
                  {link.text}
                </Link>
              ))}
            </div>
          </div>
        )}

        {/* Conversion CTA Banner */}
        {seoData && (
          <div className="glass-card p-8 mb-16 text-center bg-gradient-to-br from-[#f97316]/20 via-[#22c55e]/10 to-[#f97316]/20 border border-[#f97316]/30">
            <h2 className="text-3xl font-bold mb-3">Ready to Get {product.name}?</h2>
            <p className="text-slate-400 mb-6 max-w-xl mx-auto">
              Join 10,000+ happy customers who save up to 96% on premium subscriptions. Instant delivery. 24H money-back guarantee.
            </p>
            <div className="flex flex-wrap items-center justify-center gap-4">
              <button onClick={() => addItem(product.id)} className="btn-primary text-lg px-8 py-4 flex items-center gap-2">
                <ShoppingCart className="w-5 h-5" />{seoData.ctas[0] || `Buy ${product.name} — Save ${discount}%`}
              </button>
              <a href="https://wa.me/917038146526" target="_blank" rel="noopener noreferrer nofollow" className="px-6 py-4 rounded-full bg-green-500/10 border border-green-500/30 text-green-400 hover:bg-green-500/20 transition-all flex items-center gap-2">
                <MessageCircle className="w-5 h-5" />Buy via WhatsApp
              </a>
            </div>
            <div className="flex flex-wrap items-center justify-center gap-4 mt-4 text-xs text-slate-500">
              <span className="flex items-center gap-1"><CheckCircle2 className="w-3 h-3 text-[#22c55e]" />100% Genuine</span>
              <span className="flex items-center gap-1"><CheckCircle2 className="w-3 h-3 text-[#22c55e]" />Instant Delivery</span>
              <span className="flex items-center gap-1"><CheckCircle2 className="w-3 h-3 text-[#22c55e]" />24H Refund</span>
              <span className="flex items-center gap-1"><CheckCircle2 className="w-3 h-3 text-[#22c55e]" />10,000+ Customers</span>
            </div>
          </div>
        )}

        {/* Semantic Keywords (hidden for SEO) */}
        {seoData && (
          <div className="mb-16">
            <h2 className="text-lg font-bold mb-3 text-slate-500">Related Searches</h2>
            <div className="flex flex-wrap gap-2">
              {seoData.longTailKeywords.slice(0, 10).map((kw, i) => (
                <span key={i} className="px-3 py-1 rounded-full bg-white/5 border border-white/10 text-xs text-slate-500">
                  {kw}
                </span>
              ))}
            </div>
          </div>
        )}

        {/* Related Products */}
        {hasRelated && (
          <div>
            <h2 className="text-2xl font-bold mb-6">Related Products</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {related.map(rp => {
                const d = Math.round(((rp.originalPrice - rp.price) / rp.originalPrice) * 100)
                const ri = getProductImage(rp.slug, rp.category)
                return (
                  <Link key={rp.id} to={`/product/${rp.slug}`} className="glass-card overflow-hidden hover:border-[#f97316]/30 transition-all group">
                    <div className="h-36 overflow-hidden">
                      <img src={ri} alt={rp.name} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" loading="lazy" />
                    </div>
                    <div className="p-3">
                      <h4 className="font-medium text-sm mb-1 group-hover:text-[#f97316] transition-colors line-clamp-1">{rp.name}</h4>
                      <div className="flex items-center gap-2">
                        <span className="text-[#f97316] font-bold text-sm">${rp.price}</span>
                        <span className="text-xs text-slate-500 line-through">${rp.originalPrice}</span>
                        <span className="text-xs text-green-400">{d}%</span>
                      </div>
                    </div>
                  </Link>
                )
              })}
            </div>
          </div>
        )}
      </div>
    </div>
    </>
  )
}
