import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { useState, useEffect } from "react";
import { Header } from "@/components/site/Header";
import { SignInModal, CartDrawer, CheckoutFlow } from "@/components/site/Modals";
import { Button } from "@/components/ui/button";
import { useStore, fmt, seedProducts, type Product } from "@/lib/store";
import { slugify } from "@/lib/categories";
import { Star, Truck, ShieldCheck, RotateCcw, Minus, Plus, Video, Play, Sparkles, CheckCircle2, UserCheck } from "lucide-react";

export const Route = createFileRoute("/product/$id")({
  loader: ({ params }) => {
    const p = seedProducts.find((x) => x.id === params.id);
    return { seedProduct: p ?? null, id: params.id };
  },
  head: ({ loaderData }) => {
    const p = loaderData?.seedProduct;
    const title = p ? `${p.name} — SulejaMarket` : "Product — SulejaMarket";
    const desc = p
      ? `Buy ${p.name} for ₦${p.price.toLocaleString("en-NG")} on SulejaMarket. Fast delivery across Nigeria.`
      : "Shop this product on SulejaMarket.";
    return {
      meta: [
        { title },
        { name: "description", content: desc },
        { property: "og:title", content: title },
        { property: "og:description", content: desc },
        ...(p ? [{ property: "og:image", content: (p.images?.[0] || `https://picsum.photos/seed/${p.seed}/1200/630`) }] : []),
      ],
    };
  },
  notFoundComponent: () => (
    <div className="min-h-screen grid place-items-center p-8 text-center">
      <div>
        <h1 className="text-2xl font-bold mb-2">Product not found</h1>
        <Link to="/" className="text-orange-600 underline">Back to home</Link>
      </div>
    </div>
  ),
  errorComponent: ({ error }) => (
    <div className="min-h-screen grid place-items-center p-8 text-center">
      <div>
        <h1 className="text-xl font-bold mb-2">Something went wrong</h1>
        <p className="text-sm text-neutral-600">{error.message}</p>
      </div>
    </div>
  ),
  component: ProductPage,
});

export type Review = {
  id: string;
  product_id: string;
  order_id: string;
  user_email: string;
  user_name: string;
  rating: number;
  title: string;
  comment: string;
  video_url: string;
  created_at: number;
};

function ProductPage() {
  const { id } = Route.useParams();
  const { addToCart, getAllProducts } = useStore();
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [qty, setQty] = useState(1);
  const [activeImg, setActiveImg] = useState(0);
  const [reviews, setReviews] = useState<Review[]>([]);
  const [activeVideoModal, setActiveVideoModal] = useState<string | null>(null);

  const all = getAllProducts();
  const product: Product | undefined = all.find((p) => p.id === id);

  const [color, setColor] = useState(product?.colors?.[0] || "");
  const [size, setSize] = useState(product?.sizes?.[0] || "");

  useEffect(() => {
    if (!product) return;
    fetch(`/api/reviews.php?product_id=${product.id}`)
      .then((r) => r.json())
      .then((data) => {
        if (Array.isArray(data)) setReviews(data);
      })
      .catch(() => {});
  }, [product]);

  if (!product) {
    throw notFound();
  }

  const images = product.images && product.images.length > 0 
    ? product.images 
    : (product.images?.length ? product.images : [0, 1, 2, 3].map((i) => `https://picsum.photos/seed/${product.seed}${i}/600/600`));
  const related = all.filter((p) => p.id !== product.id && p.category === product.category).slice(0, 6);
  const fallback = all.filter((p) => p.id !== product.id).slice(0, 6);
  const you = related.length > 0 ? related : fallback;

  const handleAdd = () => {
    for (let i = 0; i < qty; i++) addToCart(product);
  };
  const handleBuyNow = () => {
    handleAdd();
    setCartOpen(true);
  };

  // Demo fallback video reviews if none created yet
  const sampleVideoReviews: Review[] = [
    {
      id: "demo1",
      product_id: product.id,
      order_id: "ORD-DEMO1",
      user_email: "amina@example.com",
      user_name: "Amina Ibrahim",
      rating: 5,
      title: "Super fast delivery to Suleja & 100% authentic!",
      comment: "I received the package directly from the vendor in 2 days. Sealed condition, tested working great!",
      video_url: "https://assets.mixkit.co/videos/preview/mixkit-unboxing-a-new-smartphone-41484-large.mp4",
      created_at: Date.now() - 86400000 * 2,
    },
    {
      id: "demo2",
      product_id: product.id,
      order_id: "ORD-DEMO2",
      user_email: "emeka@example.com",
      user_name: "Emeka Okafor",
      rating: 5,
      title: "Excellent build quality, verified vendor!",
      comment: "Very impressive item. Unboxed it on video right after receiving it from the courier.",
      video_url: "https://assets.mixkit.co/videos/preview/mixkit-hands-holding-a-smartphone-with-green-screen-41487-large.mp4",
      created_at: Date.now() - 86400000 * 5,
    }
  ];

  const displayReviews = reviews.length > 0 ? reviews : sampleVideoReviews;

  return (
    <div className="min-h-screen" style={{ backgroundColor: "#f0f2f5" }}>
      <SignInModal open={signInOpen} onOpenChange={setSignInOpen} />
      <CartDrawer open={cartOpen} onOpenChange={setCartOpen} onCheckout={() => { setCartOpen(false); setCheckoutOpen(true); }} />
      <CheckoutFlow open={checkoutOpen} onOpenChange={setCheckoutOpen} />
      <Header onOpenCart={() => setCartOpen(true)} onOpenSignIn={() => setSignInOpen(true)} />

      <main className="max-w-[1200px] mx-auto px-4 py-4 space-y-4">
        <nav className="text-xs text-neutral-500">
          <Link to="/" className="hover:text-orange-600">Home</Link>
          <span className="mx-1.5">/</span>
          {product.category && (
            <>
              <Link
                to="/category/$slug"
                params={{ slug: slugify(product.category) }}
                className="hover:text-orange-600"
              >
                {product.category}
              </Link>
              <span className="mx-1.5">/</span>
            </>
          )}
          <span className="text-neutral-800 line-clamp-1 inline">{product.name}</span>
        </nav>

        <div className="grid grid-cols-12 gap-3">
          {/* Gallery */}
          <section className="col-span-5 bg-white rounded-md p-4">
            <img
              src={images[activeImg]}
              alt={product.name}
              className="w-full aspect-square object-cover rounded"
            />
            <div className="grid grid-cols-4 gap-2 mt-3">
              {images.map((src, i) => (
                <button
                  key={i}
                  onClick={() => setActiveImg(i)}
                  className={`aspect-square rounded overflow-hidden border-2 ${activeImg === i ? "border-orange-500" : "border-transparent"}`}
                >
                  <img src={src} alt={`${product.name} view ${i + 1}`} className="w-full h-full object-cover" />
                </button>
              ))}
            </div>
          </section>

          {/* Info */}
          <section className="col-span-4 bg-white rounded-md p-4 space-y-3">
            <div className="text-xs text-neutral-500">
              Official Store · <span className="text-emerald-600 font-medium">In stock</span>
            </div>
            <h1 className="text-lg font-semibold text-neutral-800 leading-snug">{product.name}</h1>
            {product.summary && (
              <p className="text-sm text-neutral-600 mt-1">{product.summary}</p>
            )}
            <div className="flex items-center gap-2 text-sm mt-1">
              <div className="flex text-orange-500">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Star key={i} className="w-4 h-4" fill={i < 5 ? "currentColor" : "none"} />
                ))}
              </div>
              <span className="text-xs text-neutral-500">({displayReviews.length} verified video reviews)</span>
            </div>

            <div className="pt-2 border-t">
              <div className="text-2xl font-bold text-neutral-900">₦ {fmt(product.price)}</div>
              {product.old && (
                <div className="flex items-center gap-2 mt-1">
                  <span className="text-sm text-neutral-400 line-through">₦ {fmt(product.old)}</span>
                  {product.disc && (
                    <span className="bg-orange-100 text-orange-700 text-[11px] font-bold px-1.5 py-0.5 rounded">
                      {product.disc}
                    </span>
                  )}
                </div>
              )}
              <div className="text-xs text-neutral-500 mt-1">+ shipping from ₦ 1,200 to Suleja</div>
            </div>

            {product.colors && product.colors.length > 0 && (
              <div className="pt-2 border-t space-y-2">
                <div className="text-xs text-neutral-600 font-medium">Color: <span className="text-neutral-900 font-bold">{color}</span></div>
                <div className="flex gap-2 flex-wrap">
                  {product.colors.map(c => (
                    <button 
                      key={c} 
                      onClick={() => setColor(c)}
                      className={`px-3 py-1.5 text-xs font-medium rounded border ${color === c ? 'border-orange-500 bg-orange-50 text-orange-700' : 'border-neutral-200 hover:bg-neutral-50'}`}
                    >
                      {c}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {product.sizes && product.sizes.length > 0 && (
              <div className="pt-2 border-t space-y-2">
                <div className="text-xs text-neutral-600 font-medium">Size: <span className="text-neutral-900 font-bold">{size}</span></div>
                <div className="flex gap-2 flex-wrap">
                  {product.sizes.map(s => (
                    <button 
                      key={s} 
                      onClick={() => setSize(s)}
                      className={`px-3 py-1.5 text-xs font-medium rounded border ${size === s ? 'border-orange-500 bg-orange-50 text-orange-700' : 'border-neutral-200 hover:bg-neutral-50'}`}
                    >
                      {s}
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div className="pt-2 border-t space-y-2">
              <div className="text-xs text-neutral-600 font-medium">Quantity</div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setQty((q) => Math.max(1, q - 1))}
                  className="w-8 h-8 rounded border flex items-center justify-center hover:bg-neutral-50"
                  aria-label="Decrease quantity"
                >
                  <Minus className="w-4 h-4" />
                </button>
                <span className="w-10 text-center font-medium">{qty}</span>
                <button
                  onClick={() => setQty((q) => q + 1)}
                  className="w-8 h-8 rounded border flex items-center justify-center hover:bg-neutral-50"
                  aria-label="Increase quantity"
                >
                  <Plus className="w-4 h-4" />
                </button>
              </div>
            </div>

            <div className="pt-2 space-y-2">
              <Button onClick={handleAdd} className="w-full h-11 bg-orange-500 hover:bg-orange-600 text-white font-semibold">
                Add to cart
              </Button>
              <Button
                onClick={handleBuyNow}
                variant="outline"
                className="w-full h-11 border-orange-500 text-orange-600 hover:bg-orange-50 font-semibold"
              >
                Buy now
              </Button>
            </div>
          </section>

          {/* Delivery / Trust */}
          <aside className="col-span-3 bg-white rounded-md p-4 space-y-3 text-sm">
            <div className="font-semibold text-neutral-800">Delivery & Returns</div>
            <div className="flex gap-3">
              <Truck className="w-5 h-5 text-orange-500 shrink-0" />
              <div>
                <div className="font-medium text-neutral-800">Door Delivery</div>
                <div className="text-xs text-neutral-500">Delivery in 2 – 5 business days</div>
              </div>
            </div>
            <div className="flex gap-3">
              <RotateCcw className="w-5 h-5 text-orange-500 shrink-0" />
              <div>
                <div className="font-medium text-neutral-800">Free Returns</div>
                <div className="text-xs text-neutral-500">Free return within 7 days for eligible items</div>
              </div>
            </div>
            <div className="flex gap-3">
              <ShieldCheck className="w-5 h-5 text-orange-500 shrink-0" />
              <div>
                <div className="font-medium text-neutral-800">Warranty</div>
                <div className="text-xs text-neutral-500">1 year manufacturer warranty</div>
              </div>
            </div>
          </aside>
        </div>

        {/* Customer Video Reviews Section */}
        <section className="bg-white rounded-md p-5 space-y-4">
          <div className="flex items-center justify-between border-b pb-3">
            <div>
              <h2 className="text-base font-bold text-neutral-900 flex items-center gap-2">
                <Video className="w-5 h-5 text-orange-500" /> Customer Video Reviews
              </h2>
              <p className="text-xs text-neutral-500 mt-0.5">
                Real video unboxings & reviews recorded by customers who received this product.
              </p>
            </div>
            <span className="text-xs bg-orange-100 text-orange-700 font-bold px-2.5 py-1 rounded-full flex items-center gap-1">
              <Sparkles className="w-3.5 h-3.5" /> {displayReviews.length} Verified Clips
            </span>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {displayReviews.map((rev) => (
              <div key={rev.id} className="border rounded-xl p-4 bg-neutral-50/50 space-y-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 rounded-full bg-orange-500 text-white flex items-center justify-center font-bold text-xs">
                      {rev.user_name.charAt(0)}
                    </div>
                    <div>
                      <div className="text-xs font-bold text-neutral-900 flex items-center gap-1">
                        {rev.user_name}
                        <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600 fill-emerald-100" />
                      </div>
                      <div className="text-[10px] text-neutral-400">Verified Purchaser · {new Date(rev.created_at).toLocaleDateString()}</div>
                    </div>
                  </div>
                  <div className="flex text-amber-400">
                    {Array.from({ length: 5 }).map((_, i) => (
                      <Star key={i} className="w-3.5 h-3.5" fill={i < rev.rating ? "currentColor" : "none"} />
                    ))}
                  </div>
                </div>

                <div className="text-xs font-bold text-neutral-800">{rev.title}</div>

                {/* Video Player */}
                <div className="relative rounded-lg overflow-hidden bg-black aspect-video group border">
                  <video
                    src={rev.video_url}
                    controls
                    className="w-full h-full object-cover"
                  />
                </div>

                <p className="text-xs text-neutral-600 leading-relaxed">{rev.comment}</p>
              </div>
            ))}
          </div>
        </section>

        {/* Description & specs */}
        <section className="grid grid-cols-12 gap-3">
          <div className="col-span-8 bg-white rounded-md p-4 space-y-3">
            <h2 className="text-base font-semibold text-neutral-800">Product details</h2>
            <div className="text-sm text-neutral-700 leading-relaxed whitespace-pre-wrap">
              {product.description ? product.description : (
                <p>
                  {product.name} is a genuine, quality-tested item shipped directly from the vendor.
                  Enjoy competitive pricing, secure Paystack checkout and fast delivery across Nigeria.
                  Package includes the item and standard accessories.
                </p>
              )}
            </div>
            <ul className="text-sm text-neutral-700 list-disc pl-5 space-y-1 mt-4">
              <li>Category: {product.category ?? "General"}</li>
              <li>Ships from: Suleja, Niger State</li>
              <li>SKU: {product.id.toUpperCase()}</li>
              <li>Condition: Brand new</li>
            </ul>
          </div>
          <div className="col-span-4 bg-white rounded-md p-4">
            <h2 className="text-base font-semibold text-neutral-800 mb-2">Specifications</h2>
            <dl className="text-sm divide-y">
              <div className="flex justify-between py-2"><dt className="text-neutral-500">Brand</dt><dd className="text-neutral-800">Generic</dd></div>
              <div className="flex justify-between py-2"><dt className="text-neutral-500">Model</dt><dd className="text-neutral-800">{product.id.toUpperCase()}</dd></div>
              <div className="flex justify-between py-2"><dt className="text-neutral-500">Weight</dt><dd className="text-neutral-800">1.2 kg</dd></div>
              <div className="flex justify-between py-2"><dt className="text-neutral-500">Color</dt><dd className="text-neutral-800">As shown</dd></div>
            </dl>
          </div>
        </section>

        {/* Related */}
        {you.length > 0 && (
          <section className="bg-white rounded-md overflow-hidden">
            <div className="bg-orange-400 text-white px-4 py-2.5 font-semibold">You may also like</div>
            <div className="grid grid-cols-6">
              {you.map((p) => (
                <Link
                  key={p.id}
                  to="/product/$id"
                  params={{ id: p.id }}
                  className="border-r border-b last:border-r-0 p-3 bg-white hover:shadow-md transition"
                >
                  <img
                    src={(p.images?.[0] || `https://picsum.photos/seed/${p.seed}/240/240`)}
                    alt={p.name}
                    className="w-full aspect-square object-cover rounded"
                  />
                  <div className="mt-2 text-xs text-neutral-700 line-clamp-2">{p.name}</div>
                  <div className="text-sm font-bold text-neutral-900">₦ {fmt(p.price)}</div>
                </Link>
              ))}
            </div>
          </section>
        )}
      </main>
    </div>
  );
}
