"use client";

import { useQuery } from "convex/react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useCallback, useMemo, useState } from "react";
import { api } from "../../../../../convex/_generated/api";
import type { PetCategorySlug } from "@/lib/shop/constants";
import {
  filterStateFromSearchParams,
  filterStateToSearchParams,
  shopFilterStateToApiArgs,
} from "@/lib/shop/filterState";
import {
  enrichedProductToCardProps,
  type EnrichedProduct,
} from "@/lib/shop/productMapper";
import { ShopBreadcrumbBar } from "@/components/shop/ShopBreadcrumbBar";
import { ShopCategoryStrip } from "@/components/shop/ShopCategoryStrip";
import { ShopFilterModal } from "@/components/shop/ShopFilterModal";
import { ShopFilterSidebar } from "@/components/shop/ShopFilterSidebar";
import { ShopPageBanner } from "@/components/shop/ShopPageBanner";
import { ShopProductGrid } from "@/components/shop/ShopProductGrid";
import { ShopToolbar, type SortOption } from "@/components/shop/ShopToolbar";
import { ShopEmptyState } from "@/components/shop/state/ShopEmptyState";
import { ShopErrorState } from "@/components/shop/state/ShopErrorState";
import { ShopProductGridSkeleton } from "@/components/shop/state/ShopProductGridSkeleton";
import { TrustAndCredibilitySection } from "@/components/sections/TrustAndCredibility";

const SORT_OPTIONS: SortOption[] = [
  { value: "newest", label: "Newest" },
  { value: "price-asc", label: "Price: Low to High" },
  { value: "price-desc", label: "Price: High to Low" },
];

function formatCategoryTitle(slug: string): string {
  if (slug === "small-pets") return "Small Pets";
  return slug.charAt(0).toUpperCase() + slug.slice(1);
}

export function PetCategoryPage({ slug }: { slug: PetCategorySlug }) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [sort, setSort] = useState<string>("newest");
  const [filterModalOpen, setFilterModalOpen] = useState(false);

  const filterState = useMemo(
    () => filterStateFromSearchParams(searchParams),
    [searchParams],
  );
  const filterArgs = useMemo(() => shopFilterStateToApiArgs(filterState), [filterState]);

  const category = useQuery(api.categories.getBySlug, { slug });
  const subCategories = useQuery(
    api.categories.list,
    category?._id != null ? { parentId: category._id } : "skip",
  );
  const filterOptions = useQuery(api.products.getFilterOptions, {
    parentCategorySlug: slug,
  });
  const products = useQuery(api.products.listByParentSlug, {
    parentCategorySlug: slug,
    ...filterArgs,
  });

  const setFilterStateToUrl = useCallback(
    (state: typeof filterState) => {
      const params = filterStateToSearchParams(state);
      const q = params.toString();
      router.replace(q ? `${pathname}?${q}` : pathname);
    },
    [pathname, router],
  );

  const stripLinks = useMemo(() => {
    if (!subCategories || !Array.isArray(subCategories)) return [];
    return subCategories.map((c) => ({
      label: c.name,
      href: `/shop/${slug}/${c.slug}`,
    }));
  }, [subCategories, slug]);

  const sortedProducts = useMemo(() => {
    if (!products || !Array.isArray(products)) return [];
    const list = [...products] as EnrichedProduct[];
    if (sort === "newest") {
      list.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
    } else if (sort === "price-asc") {
      list.sort((a, b) => {
        const pa = a.variants?.[0]?.price ?? 0;
        const pb = b.variants?.[0]?.price ?? 0;
        return pa - pb;
      });
    } else if (sort === "price-desc") {
      list.sort((a, b) => {
        const pa = a.variants?.[0]?.price ?? 0;
        const pb = b.variants?.[0]?.price ?? 0;
        return pb - pa;
      });
    }
    return list;
  }, [products, sort]);

  const handleRetry = useCallback(() => {
    window.location.reload();
  }, []);

  const isLoading = category === undefined || (category != null && products === undefined);
  const categoryNotFound = category === null;
  const hasError = categoryNotFound;
  const isEmpty = category != null && Array.isArray(products) && products.length === 0;

  return (
    <main className="mx-auto w-full max-w-7xl min-w-0 px-4 py-6 md:px-6 md:py-8">
      {/* Top row: breadcrumb + toolbar */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <ShopBreadcrumbBar
          items={[
            { label: "Home", href: "/" },
            { label: "Shop", href: "/shop" },
            { label: category?.name ?? slug },
          ]}
        />
        <ShopToolbar
          sortOptions={SORT_OPTIONS}
          currentSort={sort}
          onSortChange={setSort}
          onOpenFilter={() => setFilterModalOpen(true)}
          resultCount={Array.isArray(products) ? products.length : undefined}
        />
      </div>

      <ShopPageBanner
        title={category?.name ?? formatCategoryTitle(slug)}
        subtitle={category?.description ?? undefined}
      />

      {hasError && (
        <ShopErrorState
          message="Category not found or failed to load."
          onRetry={handleRetry}
        />
      )}

      {!hasError && (
        <div className="mt-6 flex flex-col gap-6 lg:flex-row lg:items-start">
          <ShopFilterSidebar
            filterOptions={filterOptions ?? null}
            filterState={filterState}
            onFilterChange={setFilterStateToUrl}
            filterOptionsLoading={filterOptions === undefined}
          >
            <p className="text-sm font-medium text-[var(--foreground)]">
              Sub-categories
            </p>
            {stripLinks.length > 0 ? (
              <ul className="mt-2 space-y-1">
                {stripLinks.map((link) => (
                  <li key={link.href}>
                    <Link
                      href={link.href}
                      className="text-sm text-[var(--muted)] hover:text-[var(--foreground)] focus:outline-none focus:ring-2 focus:ring-[var(--accent)] rounded"
                    >
                      {link.label}
                    </Link>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="mt-1 text-sm text-[var(--muted)]">
                No sub-categories
              </p>
            )}
          </ShopFilterSidebar>

          <div className="min-w-0 flex-1">
            {stripLinks.length > 0 && <ShopCategoryStrip links={stripLinks} />}

            <div className="mt-6">
              {isLoading ? (
                <ShopProductGridSkeleton />
              ) : categoryNotFound ? null : isEmpty ? (
                <ShopEmptyState
                  title="No products in this category"
                  description="There are no products in this category right now."
                />
              ) : (
                <ShopProductGrid
                  products={sortedProducts.map((p) => ({
                    ...enrichedProductToCardProps(p as EnrichedProduct),
                    id: (p as { _id: string })._id,
                  }))}
                />
              )}
            <div className="mt-8">
              <TrustAndCredibilitySection />
            </div>
            </div>
          </div>
        </div>
      )}

      <ShopFilterModal
        isOpen={filterModalOpen}
        onClose={() => setFilterModalOpen(false)}
        onApply={() => setFilterModalOpen(false)}
        filterOptions={filterOptions ?? null}
        filterState={filterState}
        onApplyFilters={setFilterStateToUrl}
        filterOptionsLoading={filterOptions === undefined}
      >
        <p className="text-sm font-medium text-[var(--foreground)]">
          Sub-categories
        </p>
        {stripLinks.length > 0 ? (
          <ul className="mt-2 space-y-1">
            {stripLinks.map((link) => (
              <li key={link.href}>
                <Link
                  href={link.href}
                  className="text-sm text-[var(--muted)] hover:text-[var(--foreground)] focus:outline-none focus:ring-2 focus:ring-[var(--accent)] rounded"
                >
                  {link.label}
                </Link>
              </li>
            ))}
          </ul>
        ) : (
          <p className="mt-1 text-sm text-[var(--muted)]">
            No sub-categories
          </p>
        )}
      </ShopFilterModal>
    </main>
  );
}
