import { createFileRoute, Link } from "@tanstack/react-router";
import { useMemo, useState } from "react";

import { ProductCard } from "@/components/site/ProductCard";
import { bdt, toBn } from "@/lib/bn";
import { categories, seedProducts } from "@/lib/catalog";

type ShopSearch = { q?: string | undefined; category?: string | undefined };

export const Route = createFileRoute("/shop")({
  validateSearch: (search: Record<string, unknown>): ShopSearch => ({
    q: typeof search['q'] === "string" && search['q'] ? search['q'] : undefined,
    category:
      typeof search['category'] === "string" && search['category'] ? search['category'] : undefined,
  }),
  head: () => ({
    meta: [
      { title: "শপ | ইকোগ্রিন বিডি" },
      {
        name: "description",
        content:
          "ক্যাটাগরি, দাম ও কীওয়ার্ড অনুযায়ী খাঁটি মধু, ঘি, সরিষার তেল, খেজুর ও বাদাম খুঁজে নিন।",
      },
      { property: "og:title", content: "শপ | ইকোগ্রিন বিডি" },
      {
        property: "og:description",
        content: "সব অর্গানিক পণ্য এক জায়গায় — ফিল্টার করে সহজে কিনুন।",
      },
    ],
  }),
  component: Shop,
});

const PER_PAGE = 6;

function Shop() {
  const { q, category } = Route.useSearch();
  const [maxPrice, setMaxPrice] = useState(1600);
  const [page, setPage] = useState(1);
  const [sort, setSort] = useState("popular");

  const filtered = useMemo(() => {
    let list = seedProducts.filter((p) => p.price <= maxPrice);
    if (category) list = list.filter((p) => p.category === category);
    if (q) {
      const needle = q.trim();
      list = list.filter((p) => p.name.includes(needle) || p.short.includes(needle));
    }
    if (sort === "low") list = [...list].sort((a, b) => a.price - b.price);
    if (sort === "high") list = [...list].sort((a, b) => b.price - a.price);
    return list;
  }, [q, category, maxPrice, sort]);

  const pages = Math.max(1, Math.ceil(filtered.length / PER_PAGE));
  const current = Math.min(page, pages);
  const visible = filtered.slice((current - 1) * PER_PAGE, current * PER_PAGE);

  return (
    <div className="mx-auto max-w-6xl px-4 py-8">
      <h1 className="text-2xl font-bold">শপ</h1>
      <p className="mt-1 text-sm text-muted-foreground">
        মোট {toBn(filtered.length)} টি পণ্য পাওয়া গেছে
        {category ? ` · ক্যাটাগরি: ${category}` : ""}
        {q ? ` · খোঁজ: ${q}` : ""}
      </p>

      <div className="mt-6 grid gap-6 lg:grid-cols-[240px_1fr]">
        <aside className="space-y-6 rounded-2xl border border-border bg-card p-5">
          <div>
            <h2 className="mb-3 text-sm font-semibold">ক্যাটাগরি</h2>
            <ul className="space-y-2 text-sm">
              <li>
                <Link
                  to="/shop"
                  search={{ q, category: undefined }}
                  className={!category ? "font-semibold text-primary" : "text-muted-foreground"}
                >
                  সব পণ্য
                </Link>
              </li>
              {categories.map((c) => (
                <li key={c.slug}>
                  <Link
                    to="/shop"
                    search={{ q, category: c.slug }}
                    className={
                      category === c.slug ? "font-semibold text-primary" : "text-muted-foreground"
                    }
                  >
                    <i className={`fa-solid ${c.icon} mr-2`} aria-hidden="true" />
                    {c.name}
                  </Link>
                </li>
              ))}
            </ul>
          </div>

          <div>
            <h2 className="mb-2 text-sm font-semibold">সর্বোচ্চ দাম</h2>
            <input
              type="range"
              min={300}
              max={1600}
              step={50}
              value={maxPrice}
              onChange={(e) => {
                setMaxPrice(Number(e.target.value));
                setPage(1);
              }}
              className="w-full accent-primary"
              aria-label="সর্বোচ্চ দাম"
            />
            <p className="mt-1 text-sm font-semibold text-primary">{bdt(maxPrice)}</p>
          </div>

          <div>
            <h2 className="mb-2 text-sm font-semibold">সাজান</h2>
            <select
              value={sort}
              onChange={(e) => setSort(e.target.value)}
              aria-label="সাজান"
              className="w-full rounded-lg border border-input bg-background px-3 py-2 text-sm"
            >
              <option value="popular">জনপ্রিয়তা</option>
              <option value="low">দাম: কম থেকে বেশি</option>
              <option value="high">দাম: বেশি থেকে কম</option>
            </select>
          </div>
        </aside>

        <div>
          {visible.length === 0 ? (
            <p className="rounded-2xl border border-border bg-card p-10 text-center text-sm text-muted-foreground">
              <i className="fa-solid fa-box-open mb-3 block text-2xl" aria-hidden="true" />
              কোনো পণ্য পাওয়া যায়নি।
            </p>
          ) : (
            <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-3">
              {visible.map((p) => (
                <ProductCard key={p.id} product={p} />
              ))}
            </div>
          )}

          {pages > 1 && (
            <nav className="mt-8 flex justify-center gap-2" aria-label="পেজিনেশন">
              {Array.from({ length: pages }).map((_, i) => (
                <button
                  key={i}
                  type="button"
                  onClick={() => setPage(i + 1)}
                  className={`size-10 rounded-xl border text-sm font-semibold ${
                    current === i + 1
                      ? "border-primary bg-primary text-primary-foreground"
                      : "border-border bg-card"
                  }`}
                >
                  {toBn(i + 1)}
                </button>
              ))}
            </nav>
          )}
        </div>
      </div>
    </div>
  );
}
