import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { useState } from "react";
import { Header } from "@/components/site/Header";
import { SignInModal, CartDrawer, CheckoutFlow } from "@/components/site/Modals";
import { Button } from "@/components/ui/button";
import { BadgeCheck } from "lucide-react";
import { useStore, fmt, seedProducts, type Product } from "@/lib/store";
import {
  CATEGORIES,
  findCategoryBySlug,
  relatedCategories,
  slugify,
} from "@/lib/categories";

export const Route = createFileRoute("/category/$slug")({
  loader: ({ params }) => {
    const name = findCategoryBySlug(params.slug);
    if (!name) throw notFound();
    return { name };
  },
  head: ({ loaderData }) => {
    const title = loaderData ? `${loaderData.name} — SulejaMarket` : "Category — SulejaMarket";
    const desc = loaderData
      ? `Shop ${loaderData.name} deals on SulejaMarket. Fast delivery across Nigeria.`
      : "Browse categories on SulejaMarket.";
    return {
      meta: [
        { title },
        { name: "description", content: desc },
        { property: "og:title", content: title },
        { property: "og:description", content: desc },
      ],
    };
  },
  notFoundComponent: () => (
    <div className="min-h-screen grid place-items-center text-center p-8">
      <div>
        <h1 className="text-2xl font-bold mb-2">Category 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: CategoryPage,
});

function CategoryPage() {
  const { name } = Route.useLoaderData();
  const { addToCart, vendorProducts, getAllProducts, vendors } = useStore();
  const [signInOpen, setSignInOpen] = useState(false);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [sort, setSort] = useState<"pop" | "low" | "high">("pop");

  const wanted = relatedCategories(name).map((s) => s.toLowerCase());
  let items: Product[] =
    name === "Other categories"
      ? getAllProducts()
      : [...seedProducts, ...vendorProducts].filter((p) =>
          wanted.includes((p.category ?? "").toLowerCase()),
        );

  if (name === "Official Store" && items.length === 0) items = seedProducts.slice(0, 8);

  if (sort === "low") items = [...items].sort((a, b) => a.price - b.price);
  if (sort === "high") items = [...items].sort((a, b) => b.price - a.price);

  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>
          <span className="text-neutral-800">{name}</span>
        </nav>

        <div className="flex flex-col lg:grid lg:grid-cols-12 gap-3">
          <aside className="hidden lg:block lg:col-span-3 bg-white rounded-md py-2 text-sm h-fit">
            <div className="px-4 py-1.5 text-xs uppercase tracking-wide text-neutral-500 font-semibold">Categories</div>
            {CATEGORIES.map((c) => (
              <Link
                key={c}
                to="/category/$slug"
                params={{ slug: slugify(c) }}
                className={`block px-4 py-1.5 hover:bg-orange-50 hover:text-orange-600 ${c === name ? "bg-orange-50 text-orange-600 font-medium" : ""}`}
              >
                {c}
              </Link>
            ))}
          </aside>

          <div className="lg:col-span-9 space-y-3">
            <div className="bg-white rounded-md px-4 py-3 flex items-center justify-between">
              <div>
                <h1 className="text-lg font-bold text-neutral-800">{name}</h1>
                <div className="text-xs text-neutral-500">{items.length} products</div>
              </div>
              <label className="text-xs text-neutral-600 flex items-center gap-2">
                Sort by
                <select
                  value={sort}
                  onChange={(e) => setSort(e.target.value as typeof sort)}
                  className="border rounded px-2 py-1 text-xs"
                >
                  <option value="pop">Popularity</option>
                  <option value="low">Price: low to high</option>
                  <option value="high">Price: high to low</option>
                </select>
              </label>
            </div>

            {items.length === 0 ? (
              <div className="bg-white rounded-md p-10 text-center text-neutral-500">
                <p className="mb-2">No products in {name} yet.</p>
                <Link to="/" className="text-orange-600 underline text-sm">Explore other deals</Link>
              </div>
            ) : (
              <div className="bg-white rounded-md grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-4">
                {items.map((p) => {
                  const isVerified = vendors.find(v => v.contactEmail === p.vendorEmail)?.is_verified;
                  return (
                    <div key={p.id} className="border-r border-b last:border-r-0 p-3 bg-white hover:shadow-md transition">
                      <Link to="/product/$id" params={{ id: p.id }} className="block">
                        <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 space-y-0.5">
                          <div className="text-xs text-neutral-700 line-clamp-2 flex items-center gap-1">
                            {p.name}
                            {isVerified && <span className="inline-flex"><BadgeCheck className="w-3.5 h-3.5 text-sky-500 shrink-0" /></span>}
                          </div>
                          <div className="text-sm font-bold text-neutral-900">₦ {fmt(p.price)}</div>
                          {p.old && <div className="text-[11px] text-neutral-400 line-through">₦ {fmt(p.old)}</div>}
                        </div>
                      </Link>
                    <Button
                      onClick={() => addToCart(p)}
                      size="sm"
                      className="w-full mt-2 h-8 bg-orange-500 hover:bg-orange-600 text-white text-xs"
                    >
                      Add to cart
                    </Button>
                  </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}
