import Link from 'next/link';
import type { Metadata } from 'next';
import { getCategories, getProductsByCategory } from '@/lib/catalog';
import { ROUTES } from '@/lib/routes';
import { ProductCard } from '@/components/shop/product-card';
import { getSiteSettings, formatPrice } from '@/lib/site-settings';
import type { ApiSiteSettings } from '@/lib/backend-api';

export const metadata: Metadata = { title: 'Shop' };

interface PriceRange {
  id: string;
  min: number;
  max: number;
}

// Thresholds are fixed catalog buckets (not tied to a particular currency);
// only the displayed label is formatted using the site's configured
// currency symbol/position (§13).
const PRICE_RANGES: PriceRange[] = [
  { id: 'under-2500', min: 0, max: 2500 },
  { id: '2500-7500', min: 2500, max: 7500 },
  { id: '7500-15000', min: 7500, max: 15000 },
  { id: 'over-15000', min: 15000, max: Infinity },
];

function priceRangeLabel(range: PriceRange, currency: ApiSiteSettings['currency']): string {
  if (range.min === 0) return `Under ${formatPrice(range.max, currency)}`;
  if (range.max === Infinity) return `Over ${formatPrice(range.min, currency)}`;
  return `${formatPrice(range.min, currency)} – ${formatPrice(range.max, currency)}`;
}

interface SortOption {
  id: string;
  label: string;
}

const SORT_OPTIONS: SortOption[] = [
  { id: 'featured', label: 'Featured' },
  { id: 'price-asc', label: 'Price: Low to High' },
  { id: 'price-desc', label: 'Price: High to Low' },
  { id: 'name-asc', label: 'Name: A–Z' },
];

interface ShopSearchParams {
  category?: string;
  price?: string;
  sort?: string;
}

function buildShopHref(current: ShopSearchParams, overrides: ShopSearchParams) {
  const merged: ShopSearchParams = { ...current, ...overrides };
  const params = new URLSearchParams();
  if (merged.category) params.set('category', merged.category);
  if (merged.price) params.set('price', merged.price);
  if (merged.sort && merged.sort !== 'featured') params.set('sort', merged.sort);
  const query = params.toString();
  return query ? `${ROUTES.shop}?${query}` : ROUTES.shop;
}

export default async function ShopPage({ searchParams }: { searchParams: ShopSearchParams }) {
  const activeCategory = searchParams.category;
  const activePriceId = searchParams.price;
  const activeSort = searchParams.sort ?? 'featured';

  const activePriceRange = PRICE_RANGES.find((range) => range.id === activePriceId);

  const [categories, fetchedProducts, settings] = await Promise.all([
    getCategories(),
    getProductsByCategory(activeCategory),
    getSiteSettings(),
  ]);

  let products = fetchedProducts;

  if (activePriceRange) {
    products = products.filter((p) => p.price >= activePriceRange.min && p.price < activePriceRange.max);
  }

  products = [...products].sort((a, b) => {
    if (activeSort === 'price-asc') return a.price - b.price;
    if (activeSort === 'price-desc') return b.price - a.price;
    if (activeSort === 'name-asc') return a.name.localeCompare(b.name);
    return 0; // featured — keep catalog order
  });

  const hasActiveFilters = Boolean(activeCategory || activePriceRange);

  return (
    <>
      <section className="border-b border-navy-100 bg-beige py-10">
        <div className="container-page">
          <nav aria-label="Breadcrumb" className="mb-3 flex items-center gap-2 text-xs text-navy-600">
            <Link href={ROUTES.home} className="hover:text-gold-600">Home</Link>
            <span aria-hidden="true">/</span>
            <span className="font-medium text-navy-800">Shop</span>
          </nav>
          <h1 className="text-3xl font-serif font-bold text-navy-800">
            {activeCategory ?? 'Shop All Handicrafts'}
          </h1>
          <p className="mt-2 text-sm text-navy-600">Browse authentic, handmade pieces from artisans across Sri Lanka.</p>
        </div>
      </section>

      <section className="py-12">
        <div className="container-page grid gap-10 lg:grid-cols-[240px_1fr]">
          {/* Filters */}
          <aside className="space-y-6 lg:sticky lg:top-44 lg:self-start">
            <div className="card p-5">
              <div className="mb-3 flex items-center justify-between">
                <h3 className="font-serif text-base font-semibold text-navy-800">Categories</h3>
              </div>
              <ul className="space-y-2 text-sm">
                <li>
                  <Link
                    href={buildShopHref(searchParams, { category: undefined })}
                    className={`flex items-center justify-between rounded px-2 py-1.5 ${
                      !activeCategory ? 'bg-gold-50 font-semibold text-navy-800' : 'text-navy-600 hover:text-navy-800'
                    }`}
                  >
                    All Categories
                  </Link>
                </li>
                {categories.map((category) => (
                  <li key={category.name}>
                    <Link
                      href={buildShopHref(searchParams, { category: category.name })}
                      className={`flex items-center justify-between rounded px-2 py-1.5 ${
                        activeCategory === category.name ? 'bg-gold-50 font-semibold text-navy-800' : 'text-navy-600 hover:text-navy-800'
                      }`}
                    >
                      <span>{category.name}</span>
                      <span className="text-xs text-navy-400">{category.count}</span>
                    </Link>
                  </li>
                ))}
              </ul>
            </div>

            <div className="card p-5">
              <h3 className="mb-3 font-serif text-base font-semibold text-navy-800">Price Range</h3>
              <ul className="space-y-2 text-sm">
                <li>
                  <Link
                    href={buildShopHref(searchParams, { price: undefined })}
                    className={`flex items-center rounded px-2 py-1.5 ${
                      !activePriceId ? 'bg-gold-50 font-semibold text-navy-800' : 'text-navy-600 hover:text-navy-800'
                    }`}
                  >
                    Any Price
                  </Link>
                </li>
                {PRICE_RANGES.map((range) => (
                  <li key={range.id}>
                    <Link
                      href={buildShopHref(searchParams, { price: range.id })}
                      className={`flex items-center rounded px-2 py-1.5 ${
                        activePriceId === range.id ? 'bg-gold-50 font-semibold text-navy-800' : 'text-navy-600 hover:text-navy-800'
                      }`}
                    >
                      {priceRangeLabel(range, settings.currency)}
                    </Link>
                  </li>
                ))}
              </ul>
            </div>

            {hasActiveFilters && (
              <Link href={ROUTES.shop} className="block text-center text-sm font-medium text-gold-600 hover:text-gold-700">
                Clear All Filters
              </Link>
            )}
          </aside>

          {/* Product grid */}
          <div>
            <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
              <p className="text-sm text-navy-600">
                {products.length} product{products.length === 1 ? '' : 's'}
                {activeCategory ? ` in ${activeCategory}` : ''}
                {activePriceRange ? ` · ${priceRangeLabel(activePriceRange, settings.currency)}` : ''}
              </p>
              <div className="flex flex-wrap gap-2">
                {SORT_OPTIONS.map((option) => (
                  <Link
                    key={option.id}
                    href={buildShopHref(searchParams, { sort: option.id })}
                    className={`rounded-full border px-3 py-1.5 text-xs font-medium transition ${
                      activeSort === option.id
                        ? 'border-navy-800 bg-navy-800 text-white'
                        : 'border-navy-100 text-navy-600 hover:border-gold-500 hover:text-navy-800'
                    }`}
                  >
                    {option.label}
                  </Link>
                ))}
              </div>
            </div>

            {products.length ? (
              <div className="grid grid-cols-2 gap-6 sm:grid-cols-3 xl:grid-cols-4">
                {products.map((product) => (
                  <ProductCard key={product.slug} product={product} currency={settings.currency} />
                ))}
              </div>
            ) : (
              <div className="card p-10 text-center text-navy-600">
                <p>No products found for this filter combination.</p>
                <Link href={ROUTES.shop} className="mt-3 inline-block text-sm font-medium text-gold-600 hover:text-gold-700">
                  Clear filters
                </Link>
              </div>
            )}
          </div>
        </div>
      </section>
    </>
  );
}
