import type { QueryShopProductsResult } from '@/lib/shop/queryProducts'
import type { ParsedShopSearchParams } from '@/utilities/shopParams'

import Link from 'next/link'

import { Grid } from '@/components/Grid'
import { ProductGridItem } from '@/components/ProductGridItem'
import type { ShopFilterLabels } from '@/lib/shop/filterLabels'
import { createUrl } from '@/utilities/createUrl'
import { buildShopSearchParams } from '@/utilities/shopParams'
import {
  emptyShopFilterLabels,
  getShopClearFiltersHref,
  getShopFilterChips,
} from './shopActiveFilters'
import { shopProductGridClassName } from './shopProductGridClasses'

type ShopProductResultsProps = {
  filterLabels?: ShopFilterLabels
  products: QueryShopProductsResult
}

const getRangeText = (products: QueryShopProductsResult): string => {
  if (products.totalDocs === 0) {
    return 'No products found'
  }

  const noun = products.totalDocs === 1 ? 'product' : 'products'

  return `Showing ${products.docs.length} of ${products.totalDocs} ${noun}`
}

export function ShopProductResults({
  filterLabels = emptyShopFilterLabels,
  products,
}: ShopProductResultsProps) {
  const searchValue = products.filters.q
  const filterChips = getShopFilterChips({
    filterLabels,
    filters: products.filters,
  })
  const hasActiveState = filterChips.length > 0 || products.page > 1
  const clearFiltersHref = getShopClearFiltersHref(products.filters)
  const nextPageHref = products.hasNextPage
    ? createUrl(
        '/shop',
        buildShopSearchParams({
          ...products.filters,
          page: products.page + 1,
        }),
      )
    : null

  return (
    <div>
      <div className="mb-6 rounded-xl border border-[#dbe8d7]/70 bg-[#fbfdf8] p-4 shadow-sm shadow-[#003b29]/5">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
          <div>
            <p className="text-[10px] font-bold uppercase tracking-[0.2em] text-[#607668]">
              Results
            </p>
            <p className="mt-1 text-sm font-semibold text-[#063f2b] dark:text-neutral-100">
              {getRangeText(products)}
            </p>
            {searchValue ? (
              <p className="mt-1 text-xs text-neutral-600 dark:text-neutral-400">
                Search query: <span className="font-semibold">&quot;{searchValue}&quot;</span>
              </p>
            ) : null}
          </div>

          {hasActiveState && (
            <a
              className="inline-flex w-fit items-center justify-center rounded-full border border-[#dbe8d7] bg-white px-3 py-1.5 text-xs font-bold text-[#14422d] transition hover:border-[#14422d] hover:bg-[#edf5e8]"
              href={clearFiltersHref}
            >
              Clear all filters
            </a>
          )}
        </div>

        {filterChips.length > 0 && (
          <div className="mt-4 flex flex-wrap gap-2 border-t border-[#dbe8d7]/70 pt-3">
            {filterChips.map((chip) => (
              <a
                aria-label={`Remove ${chip.label}`}
                className="inline-flex items-center rounded-full border border-[#b9d8c2] bg-[#edf5e8] px-3 py-1 text-[11px] font-semibold text-[#063f2b] transition hover:border-[#14422d] hover:bg-white dark:border-neutral-800 dark:text-neutral-300 dark:hover:border-neutral-100 dark:hover:text-white"
                href={chip.href}
                key={`${chip.label}-${chip.href}`}
              >
                {chip.label}
                <span aria-hidden="true" className="ml-2">
                  x
                </span>
              </a>
            ))}
          </div>
        )}
      </div>

      {!searchValue && products.totalDocs === 0 && (
        <div className="mb-6 rounded-xl border border-[#dbe8d7]/70 bg-white p-6 text-sm text-neutral-700 shadow-sm">
          No products found. Please try different filters.
        </div>
      )}

      {products.docs.length > 0 ? (
        <Grid className={shopProductGridClassName}>
          {products.docs.map((product) => {
            return <ProductGridItem key={product.id} product={product} />
          })}
        </Grid>
      ) : null}

      {products.totalPages > 1 ? (
        <div className="mt-10 flex flex-col items-center justify-center gap-3 rounded-xl border border-[#dbe8d7]/70 bg-[#fbfdf8] p-4 text-sm shadow-sm shadow-[#003b29]/5">
          <p className="text-xs font-semibold uppercase tracking-[0.16em] text-[#607668]">
            {products.hasNextPage
              ? `${products.totalDocs - products.docs.length} products remaining`
              : 'All products loaded'}
          </p>

          {nextPageHref ? (
            <Link
              className="inline-flex items-center rounded-full border border-[#14422d] bg-[#063f2b] px-6 py-2.5 text-xs font-bold text-white transition hover:bg-[#14422d]"
              href={nextPageHref}
            >
              Load More
            </Link>
          ) : null}
        </div>
      ) : null}
    </div>
  )
}
