import { useParams, Link } from "react-router";
import { useCartStore } from "@/store/cartStore";
import { staticProducts } from "@/data/staticProducts";
import {
  ShoppingCart,
  Check,
  Star,
  ArrowLeft,
  MessageCircle,
  Send,
  Clock,
  Shield,
  Headphones,
  Lock,
  Sparkles,
  ChevronRight,
} from "lucide-react";
import { toast } from "sonner";

export default function ProductDetail() {
  const { slug } = useParams<{ slug: string }>();
  const addItem = useCartStore((s) => s.addItem);

  const product = staticProducts.find((p) => p.slug === slug);

  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]">Back to Shop</Link>
        </div>
      </main>
    );
  }

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

  // Build derived data with fallbacks
  const badges: string[] = product.features?.slice(0, 4) || [];
  const useCases: string[] = product.benefits || [];
  const idealFor: string[] = product.plans || [];
  const trustBadges = [
    "Private Account",
    "1-Year Warranty",
    "24/7 Support",
    "Instant Delivery",
  ];
  const reviewHighlights = product.reviews?.slice(0, 4).map((r) => r.text) || [];
  const specs: Record<string, string> = {
    "Product Type": product.productType?.replace("_", " ") || "Private Account",
    "Delivery": product.deliveryTime || "1-2 hours",
    "Warranty": "1 Year",
    "Activation": product.activation || "Email credentials",
    "Category": product.categoryName || "Software",
  };
  const breadcrumbs = [
    { label: "Home", url: "/" },
    { label: "Shop", url: "/shop" },
    { label: product.categoryName, url: `/shop?category=${product.categorySlug}` },
    { label: product.name, url: "" },
  ];

  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 generateWhatsAppLink = () => {
    const text = `Hi! I want to order ${product.name}%0A%0AOriginal Price: $${originalPrice}%0ADiscounted Price: $${salePrice}%0ADiscount: ${discount}%25%0A%0APlease help me proceed with the order.`;
    return `https://wa.me/917038146526?text=${text}`;
  };

  return (
    <main className="min-h-screen bg-[#050505] pt-24 pb-16">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Breadcrumbs */}
        <nav className="flex items-center gap-2 text-sm mb-6">
          {breadcrumbs.map((crumb, i) => (
            <span key={i} className="flex items-center gap-2">
              {i > 0 && <ChevronRight className="w-3 h-3 text-[#a5a5a5]" />}
              {crumb.url ? (
                <Link to={crumb.url} className={`${i === breadcrumbs.length - 1 ? "text-white" : "text-[#a5a5a5] hover:text-[#5b9aff]"} transition-colors`}>
                  {crumb.label}
                </Link>
              ) : (
                <span className="text-white">{crumb.label}</span>
              )}
            </span>
          ))}
        </nav>

        <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" />
          Back to Shop
        </Link>

        {/* HERO SECTION */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 mb-16">
          {/* Image */}
          <div className="glass-card rounded-2xl overflow-hidden">
            <div className="relative aspect-video">
              <img src={images[0] || "/products/canva-pro-1-year.jpg"} alt={product.imageAlt || product.name} className="w-full h-full object-cover" />
              {discount > 0 && <div className="absolute top-4 left-4 px-3 py-1.5 bg-[#ff6b6b] text-white text-sm font-bold rounded-full">Save {discount}%</div>}
              {product.badge && <div className="absolute top-4 right-4 px-3 py-1.5 bg-[#5b9aff] text-white text-sm font-bold rounded-full">{product.badge}</div>}
            </div>
          </div>

          {/* Details */}
          <div>
            {/* SKU */}
            <p className="text-xs text-[#a5a5a5] mb-2">SKU: DST-{String(product.id).padStart(4, "0")}</p>

            {/* Title & Tagline */}
            <h1 className="text-3xl sm:text-4xl font-bold text-white mb-2">{product.name}</h1>
            <p className="text-[#5b9aff] text-sm font-medium mb-4">{product.shortDesc}</p>

            {/* Rating */}
            <div className="flex items-center gap-3 mb-6">
              <div className="flex items-center gap-0.5">
                {[...Array(5)].map((_, i) => <Star key={i} className={`w-4 h-4 ${i < 5 ? "fill-[#5b9aff] text-[#5b9aff]" : "text-[#a5a5a5]"}`} />)}
              </div>
              <span className="text-sm text-white font-medium">4.9</span>
              <span className="text-sm text-[#a5a5a5]">(2,847 reviews)</span>
              <span className="text-sm text-green-400 ml-2">50,000+ sold</span>
            </div>

            {/* Price */}
            <div className="flex items-baseline gap-4 mb-6">
              <span className="text-4xl font-bold text-white">${salePrice}</span>
              {discount > 0 && <>
                <span className="text-xl text-[#a5a5a5] line-through">${originalPrice}</span>
                <span className="px-3 py-1 bg-[#ff6b6b]/20 text-[#ff6b6b] text-sm font-bold rounded-full">{discount}% OFF</span>
              </>}
            </div>

            {/* Short Description */}
            <p className="text-[#a5a5a5] mb-6 leading-relaxed">{product.description}</p>

            {/* Badges */}
            {badges.length > 0 && (
              <div className="flex flex-wrap gap-2 mb-6">
                {badges.map((badge, i) => badge && (
                  <span key={i} className="px-3 py-1 text-xs bg-white/5 text-[#a5a5a5] rounded-full">{badge}</span>
                ))}
              </div>
            )}

            {/* Trust Badges Row */}
            <div className="grid grid-cols-2 gap-3 mb-8">
              {trustBadges.map((badge, i) => (
                <div key={i} className="flex items-center gap-2 text-sm text-[#a5a5a5]">
                  <Check className="w-3.5 h-3.5 text-green-400 shrink-0" />
                  {badge}
                </div>
              ))}
            </div>

            {/* CTAs */}
            <div className="space-y-3">
              <button onClick={handleAddToCart} className="w-full flex items-center justify-center gap-2 py-4 bg-[#5b9aff] text-[#050505] font-semibold rounded-full hover:glow-blue-strong transition-all text-lg">
                <ShoppingCart className="w-5 h-5" />
                Add to Cart — ${salePrice}
              </button>
              <div className="grid grid-cols-2 gap-3">
                <a href={generateWhatsAppLink()} target="_blank" rel="noopener noreferrer" className="flex items-center justify-center gap-2 py-3 bg-[#25d366]/10 border border-[#25d366]/30 text-[#25d366] font-medium rounded-full hover:bg-[#25d366]/20 transition-all">
                  <MessageCircle className="w-4 h-4" />
                  Order on WhatsApp
                </a>
                <a href="https://t.me/mfatool" target="_blank" rel="noopener noreferrer" className="flex items-center justify-center gap-2 py-3 bg-[#0088cc]/10 border border-[#0088cc]/30 text-[#0088cc] font-medium rounded-full hover:bg-[#0088cc]/20 transition-all">
                  <Send className="w-4 h-4" />
                  Order on Telegram
                </a>
              </div>
            </div>
          </div>
        </div>

        {/* WHAT'S INCLUDED */}
        {product.features && product.features.length > 0 && (
          <section className="mb-16">
            <h2 className="text-2xl font-bold text-white mb-6">What&apos;s Included</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {product.features.map((item, i) => (
                <div key={i} className="flex items-start gap-3 glass-card rounded-xl p-4">
                  <Check className="w-5 h-5 text-green-400 shrink-0 mt-0.5" />
                  <span className="text-sm text-[#a5a5a5]">{item}</span>
                </div>
              ))}
            </div>
          </section>
        )}

        {/* SPECIFICATIONS */}
        {Object.keys(specs).length > 0 && (
          <section className="mb-16">
            <h2 className="text-2xl font-bold text-white mb-6">Product Specifications</h2>
            <div className="glass-card rounded-2xl overflow-hidden">
              <table className="w-full">
                <tbody>
                  {Object.entries(specs).map(([key, value], i) => (
                    <tr key={i} className={i % 2 === 0 ? "bg-white/[0.02]" : ""}>
                      <td className="px-6 py-3 text-sm text-[#a5a5a5] w-1/3">{key}</td>
                      <td className="px-6 py-3 text-sm text-white">{value}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        )}

        {/* INFO GRID: Delivery, Warranty, Type, Stock */}
        <section className="mb-16">
          <h2 className="text-2xl font-bold text-white mb-6">Delivery & Support</h2>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            {[
              { icon: Clock, label: "Delivery Time", value: product.deliveryTime || "1-2 hours" },
              { icon: Shield, label: "Warranty", value: "1 Year" },
              { icon: Headphones, label: "Support", value: "24/7 WhatsApp" },
              { icon: Lock, label: "Account Type", value: product.productType ? product.productType.replace("_", " ") : "Private" },
            ].map((item, i) => (
              <div key={i} className="glass-card rounded-xl p-5 text-center">
                <item.icon className="w-8 h-8 text-[#5b9aff] mx-auto mb-3" />
                <p className="text-xs text-[#a5a5a5] mb-1">{item.label}</p>
                <p className="text-sm font-semibold text-white">{item.value}</p>
              </div>
            ))}
          </div>
        </section>

        {/* USE CASES */}
        {useCases.length > 0 && (
          <section className="mb-16">
            <h2 className="text-2xl font-bold text-white mb-6">Use Cases</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
              {useCases.map((uc, i) => (
                <div key={i} className="glass-card rounded-xl p-5 hover:border-[#5b9aff]/30 transition-all">
                  <Sparkles className="w-5 h-5 text-[#5b9aff] mb-3" />
                  <p className="text-sm text-[#a5a5a5]">{uc}</p>
                </div>
              ))}
            </div>
          </section>
        )}

        {/* IDEAL FOR */}
        {idealFor.length > 0 && (
          <section className="mb-16">
            <h2 className="text-2xl font-bold text-white mb-6">Who Is This For?</h2>
            <div className="flex flex-wrap gap-3">
              {idealFor.map((user, i) => (
                <span key={i} className="px-4 py-2 bg-[#5b9aff]/10 text-[#5b9aff] rounded-full text-sm font-medium">
                  {user}
                </span>
              ))}
            </div>
          </section>
        )}

        {/* REVIEW HIGHLIGHTS */}
        {reviewHighlights.length > 0 && (
          <section className="mb-16">
            <h2 className="text-2xl font-bold text-white mb-6">What Customers Say</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {reviewHighlights.map((review, i) => (
                <div key={i} className="glass-card rounded-xl p-5">
                  <div className="flex items-center gap-1 mb-3">
                    {[...Array(5)].map((_, j) => <Star key={j} className="w-3 h-3 fill-[#5b9aff] text-[#5b9aff]" />)}
                  </div>
                  <p className="text-sm text-[#a5a5a5] italic">&quot;{review.replace(/"/g, "")}&quot;</p>
                </div>
              ))}
            </div>
          </section>
        )}

        {/* FAQ */}
        {product.faqs && product.faqs.length > 0 && (
          <section className="mb-16">
            <h2 className="text-2xl font-bold text-white mb-6">Frequently Asked Questions</h2>
            <div className="space-y-3">
              {product.faqs.map((faq, i) => (
                <div key={i} className="glass-card rounded-xl p-5">
                  <h3 className="font-semibold text-white mb-2">{faq.q}</h3>
                  <p className="text-sm text-[#a5a5a5]">{faq.a}</p>
                </div>
              ))}
            </div>
          </section>
        )}

        {/* DISCLAIMER */}
        <section className="mb-16">
          <div className="glass-card rounded-2xl p-6 border-l-4 border-[#5b9aff]">
            <h3 className="text-lg font-semibold text-white mb-2">Our Promise</h3>
            <p className="text-sm text-[#a5a5a5] leading-relaxed">
              Deal Stack Tools only provides legitimate private accounts. We do not deal in cracked software, shared cookies, or illegally obtained credentials. All accounts come with a 1-year warranty and 24/7 WhatsApp support. These are genuine accounts purchased through official channels — you get full access with your own login credentials.
            </p>
          </div>
        </section>

        {/* CTA SECTION */}
        <section className="mb-16 glass-card rounded-2xl p-8 text-center bg-gradient-to-br from-[#5b9aff]/10 to-transparent border-[#5b9aff]/30">
          <h2 className="text-2xl sm:text-3xl font-bold text-white mb-4">Ready to Get {product.name}?</h2>
          <p className="text-[#a5a5a5] mb-6 max-w-lg mx-auto">Join 50,000+ happy customers who trust Deal Stack Tools. Premium access, unbeatable prices, guaranteed satisfaction.</p>
          <div className="flex flex-col sm:flex-row items-center justify-center gap-4">
            <button onClick={handleAddToCart} className="flex items-center justify-center gap-2 px-8 py-4 bg-[#5b9aff] text-[#050505] font-semibold rounded-full hover:glow-blue-strong transition-all text-lg">
              <ShoppingCart className="w-5 h-5" />
              Add to Cart — ${salePrice}
            </button>
            <a href={generateWhatsAppLink()} target="_blank" rel="noopener noreferrer" className="flex items-center justify-center gap-2 px-8 py-4 bg-[#25d366]/20 border border-[#25d366]/40 text-[#25d366] font-semibold rounded-full hover:bg-[#25d366]/30 transition-all">
              <MessageCircle className="w-5 h-5" />
              Order via WhatsApp
            </a>
          </div>
          <p className="text-xs text-[#a5a5a5] mt-4">Delivery in {product.deliveryTime || "1-2 hours"} &middot; 1-Year Warranty &middot; 24/7 Support</p>
        </section>

        {/* Footer Note */}
        <section className="mb-8">
          <p className="text-center text-sm text-[#ff6b6b]/80 bg-[#ff6b6b]/5 rounded-xl p-4">
            <strong>Note:</strong> Nothing is lifetime. Every product includes 1-year validity &amp; 1-year support. If we mention &quot;lifetime&quot;, it means 1-year warranty only. Please keep this in mind while purchasing. We do not sell cracked or stolen accounts. All accounts are legitimate private accounts purchased through official channels.
          </p>
        </section>
      </div>
    </main>
  );
}
