"use client";

import Link from "next/link";
import { useParams } from "next/navigation";
import { useMemo, useState } from "react";
import { MainHeader } from "@/components/layout/main-header";
import { ArticleCard } from "@/components/shared/article-card";
import { MainFooter } from "@/components/shared/main-footer";
import { SearchBar } from "@/components/shared/search-bar";
import { SortDropdown } from "@/components/shared/sort-dropdown";
import { StoreCard } from "@/components/shared/store-card";
import { EmptyState } from "@/components/ui/empty-state";
import { Pagination } from "@/components/ui/pagination";
import { SectionHeader } from "@/components/ui/section-header";
import { Skeleton } from "@/components/ui/skeleton";
import { useArticlesQuery, useCategoriesQuery, useStoresQuery } from "@/hooks/queries/api-hooks";
import { pickLocalizedText } from "@/lib/utils/i18n";
import { useLocale } from "@/providers/locale-provider";

export default function CategoryDetailsPage() {
  const params = useParams<{ slug: string }>();
  const { locale, selectedCountryId } = useLocale();
  const isArabic = locale === "ar";
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState("");
  const [sort, setSort] = useState("sort_order");

  const categoriesQuery = useCategoriesQuery({ per_page: 100, country_id: selectedCountryId || undefined });

  const category = useMemo(
    () => categoriesQuery.data?.items.find((item) => item.slug === params.slug),
    [categoriesQuery.data?.items, params.slug],
  );

  const storesQueryByCountry = useStoresQuery({
    category_id: category?.id,
    country_id: selectedCountryId || undefined,
    page,
    per_page: 12,
    sort,
    search: search || undefined,
  });

  const storesQueryAllCountries = useStoresQuery({
    category_id: category?.id,
    page,
    per_page: 12,
    sort,
    search: search || undefined,
  });

  const hasCountryFilteredResults = (storesQueryByCountry.data?.items.length ?? 0) > 0;
  const useFallbackAllCountries = Boolean(selectedCountryId) && !hasCountryFilteredResults;
  const activeStoresQuery = useFallbackAllCountries ? storesQueryAllCountries : storesQueryByCountry;

  const relatedArticlesQuery = useArticlesQuery({
    per_page: 3,
    search: pickLocalizedText(category, "name_ar", "name_en", locale, "") || undefined,
    sort: "latest",
  });

  return (
    <div>
      <MainHeader />
      <main className="container-shell section-space space-y-6">
        {categoriesQuery.isLoading ? (
          <Skeleton className="h-20" />
        ) : category ? (
          <SectionHeader
            title={pickLocalizedText(category, "name_ar", "name_en", locale, isArabic ? "القسم" : "Category")}
            subtitle={isArabic ? "استكشف المتاجر والعروض ضمن هذا القسم" : "Explore stores and offers in this category"}
          />
        ) : (
          <EmptyState
            title={isArabic ? "القسم غير موجود" : "Category not found"}
            description={isArabic ? "تعذر العثور على هذا القسم." : "We could not find this category."}
          />
        )}

        {category ? (
          <>
            <div className="surface-card grid grid-cols-1 gap-3 p-4 lg:grid-cols-3">
              <SearchBar
                value={search}
                onChange={(value) => {
                  setSearch(value);
                  setPage(1);
                }}
                placeholder={isArabic ? "ابحث داخل القسم" : "Search in category"}
              />
              <SortDropdown
                value={sort}
                onChange={(value) => {
                  setSort(value);
                  setPage(1);
                }}
                options={[
                  { value: "sort_order", label: isArabic ? "الترتيب الافتراضي" : "Default order" },
                  { value: "latest", label: isArabic ? "الأحدث" : "Latest" },
                  { value: "alphabetical", label: isArabic ? "أبجديًا" : "Alphabetical" },
                ]}
              />
            </div>

            <section>
              {activeStoresQuery.isLoading ? (
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                  {Array.from({ length: 6 }).map((_, i) => (
                    <Skeleton key={i} className="h-32" />
                  ))}
                </div>
              ) : activeStoresQuery.data && activeStoresQuery.data.items.length > 0 ? (
                <>
                  {useFallbackAllCountries ? (
                    <div className="mb-3 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-800">
                      {isArabic
                        ? "لا توجد متاجر في هذا القسم للدولة المختارة حاليًا، تم عرض النتائج من كل الدول."
                        : "No stores in this category for the selected country, showing results from all countries."}
                    </div>
                  ) : null}
                  <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    {activeStoresQuery.data.items.map((store) => (
                      <Link key={store.id} href={`/stores/${store.slug}`}>
                        <StoreCard store={store} />
                      </Link>
                    ))}
                  </div>
                  <Pagination current={activeStoresQuery.data.meta.current_page} last={activeStoresQuery.data.meta.last_page} onChange={setPage} />
                </>
              ) : (
                <EmptyState
                  title={isArabic ? "لا توجد متاجر في هذا القسم" : "No stores in this category"}
                  description={isArabic ? "جرّب فلترًا مختلفًا أو عد لاحقًا." : "Try another filter or come back later."}
                />
              )}
            </section>

            <section className="surface-card p-4">
              <SectionHeader
                title={isArabic ? "مقالات ذات صلة" : "Related Articles"}
                subtitle={isArabic ? "محتوى مرتبط بهذا القسم" : "Helpful content related to this category"}
              />
              {relatedArticlesQuery.data?.items?.length ? (
                <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                  {relatedArticlesQuery.data.items.map((article) => (
                    <ArticleCard key={`category-related-article-${article.id}`} article={article} locale={locale} />
                  ))}
                </div>
              ) : (
                <EmptyState
                  title={isArabic ? "لا توجد مقالات" : "No articles"}
                  description={isArabic ? "لا يوجد محتوى مرتبط حاليًا." : "No related content available right now."}
                />
              )}
            </section>
          </>
        ) : null}
      </main>
      <MainFooter />
    </div>
  );
}
