import { useParams, Link, useLocation } from "react-router";
import { trpc } from "@/providers/trpc";
import { useCartStore } from "@/store/cartStore";
import { ShoppingCart, ArrowLeft, MessageCircle, Check } from "lucide-react";
import { toast } from "sonner";

// Programmatic SEO page for /cheap/:slug, /buy/:slug, /affordable/:slug
export default function CheapProduct() {
  const { slug } = useParams<{ slug: string }>();
  const location = useLocation();
  const pathType = location.pathname.split("/")[1]; // cheap, buy, affordable
  const { data: product } = trpc.product.getBySlug.useQuery({ slug: slug || "" }, { enabled: !!slug });
  const addItem = useCartStore((s) => s.addItem);

  const pathLabels: Record<string, string> = { cheap: "Cheap", buy: "Buy", affordable: "Affordable" };
  const pageLabel = pathLabels[pathType] || "Best Deal";

  if (!product) {
    return (
      <main className="min-h-screen bg-[#050505] pt-24 pb-16 flex items-center justify-center">
        <div className="text-center">
          <p className="text-xl text-white mb-4">Product not found</p>
          <Link to="/shop" className="text-[#5b9aff] hover:text-[#8fb8ff]">Browse All Products</Link>
        </div>
      </main>
    );
  }

  const images = product.images ? JSON.parse(product.images) : [];
  const originalPrice = parseFloat(product.originalPrice);
  const salePrice = parseFloat(product.salePrice);
  const discount = originalPrice > salePrice ? Math.round(((originalPrice - salePrice) / originalPrice) * 100) : 0;

  const handleAddToCart = () => {
    addItem({ productId: product.id, name: product.name, slug: product.slug, price: salePrice, originalPrice, image: images[0] || "", productType: product.productType });
    toast.success(`${product.name} added to cart!`);
  };

  const metaTitle = `${pageLabel} ${product.name} — ${discount}% OFF | Deal Stack Tools`;
  const metaDesc = `${pageLabel} ${product.name} at ${discount}% off. Private account, instant delivery. 50,000+ happy customers. 1-year warranty.`;

  return (
    <main className="min-h-screen bg-[#050505] pt-24 pb-16">
      {/* Meta */}
      <title>{metaTitle}</title>
      <meta name="description" content={metaDesc} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify({
        "@context": "https://schema.org", "@type": "Product", name: product.name,
        description: metaDesc, offers: { "@type": "Offer", price: salePrice, priceCurrency: "USD", availability: "https://schema.org/InStock" }
      })}} />

      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <Link to="/shop" className="inline-flex items-center gap-2 text-sm text-[#a5a5a5] hover:text-white mb-6 transition-colors"><ArrowLeft className="w-4 h-4" /> Browse All Products</Link>

        <div className="glass-card rounded-2xl overflow-hidden">
          <div className="relative aspect-[21/9] overflow-hidden">
            <img src={images[0] || "/products/canva-pro.jpg"} alt={product.name} className="w-full h-full object-cover" />
            <div className="absolute inset-0 bg-gradient-to-t from-[#050505] via-[#050505]/50 to-transparent" />
            <div className="absolute bottom-0 left-0 right-0 p-6">
              <span className="px-3 py-1 bg-[#ff6b6b] text-white text-xs font-bold rounded-full">{pageLabel} {product.name} — {discount}% OFF</span>
              <h1 className="text-2xl sm:text-3xl font-bold text-white mt-3">{pageLabel} {product.name} at the Best Price</h1>
              <p className="text-sm text-[#a5a5a5] mt-1">Private account &middot; Instant delivery &middot; 1-year warranty</p>
            </div>
          </div>
          <div className="p-6">
            <div className="flex items-baseline gap-4 mb-4">
              <span className="text-3xl font-bold text-white">${salePrice}</span>
              <span className="text-lg text-[#a5a5a5] line-through">${originalPrice}</span>
              <span className="px-3 py-1 bg-green-500/20 text-green-400 text-sm font-bold rounded-full">Save {discount}%</span>
            </div>
            <p className="text-sm text-[#a5a5a5] leading-relaxed mb-6">{product.description}</p>
            <div className="flex flex-wrap gap-2 mb-6">
              {["Private Account", "1-Year Warranty", "Instant Delivery", "24/7 Support"].map((badge) => (
                <span key={badge} className="flex items-center gap-1 text-xs text-green-400 bg-green-500/10 px-3 py-1 rounded-full"><Check className="w-3 h-3" />{badge}</span>
              ))}
            </div>
            <div className="flex flex-col sm:flex-row gap-3">
              <button onClick={handleAddToCart} className="flex-1 flex items-center justify-center gap-2 py-4 bg-[#5b9aff] text-[#050505] font-semibold rounded-full hover:glow-blue-strong transition-all">
                <ShoppingCart className="w-5 h-5" /> Add to Cart — ${salePrice}
              </button>
              <a href={`https://wa.me/917038146526?text=Hi! I want to buy ${product.name} at $${salePrice}`} target="_blank" rel="noopener noreferrer" className="flex items-center justify-center gap-2 py-4 bg-[#25d366]/10 border border-[#25d366]/30 text-[#25d366] font-medium rounded-full hover:bg-[#25d366]/20 transition-all">
                <MessageCircle className="w-5 h-5" /> Order on WhatsApp
              </a>
            </div>
          </div>
        </div>

        {/* SEO Content */}
        <div className="mt-8 glass-card rounded-2xl p-6">
          <h2 className="text-lg font-semibold text-white mb-3">Why Buy {product.name} From Deal Stack Tools?</h2>
          <p className="text-sm text-[#a5a5a5] leading-relaxed mb-4">Get {product.name} at {discount}% off the regular price. We provide a private account with full access to all premium features. Delivery takes 2-10 minutes via WhatsApp. Every purchase includes a 1-year warranty and 24/7 support.</p>
          <div className="grid grid-cols-2 gap-3">
            {[`${pageLabel} ${product.name} India`, `${pageLabel} ${product.name} USA`, `${pageLabel} ${product.name} UK`, `Best ${product.name} deal online`].map((kw) => (
              <span key={kw} className="text-xs text-[#5b9aff] bg-[#5b9aff]/10 px-3 py-2 rounded-lg">{kw}</span>
            ))}
          </div>
        </div>
      </div>
    </main>
  );
}
