"use client";

import Link from "next/link";
import { useMemo, useState } from "react";
import { MainHeader } from "@/components/layout/main-header";
import { MainFooter } from "@/components/shared/main-footer";
import { CashbackCard } from "@/components/shared/cashback-card";
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 { useActivateCashbackMutation, useCashbackHistoryQuery, useCashbackOffersQuery, useCashbackStoresQuery, useCashbackSummaryQuery, useCategoriesQuery } from "@/hooks/queries/api-hooks";
import { CategorySidebar } from "@/components/shared/category-sidebar";
import { PageHero } from "@/components/shared/page-hero";
import { useLocale } from "@/providers/locale-provider";
import { useAuth } from "@/providers/auth-provider";
import { useToast } from "@/providers/toast-provider";
import { getApiErrorMessage } from "@/lib/api/client";
import { useRouter } from "next/navigation";

export default function CashbackPage() {
  const [pageStores, setPageStores] = useState(1);
  const [pageOffers, setPageOffers] = useState(1);
  const [pageHistory, setPageHistory] = useState(1);
  const [activatingOfferId, setActivatingOfferId] = useState<number | null>(null);
  const [search, setSearch] = useState("");
  const [sort, setSort] = useState("sort_order");
  const { selectedCountryId, locale } = useLocale();
  const { isAuthenticated } = useAuth();
  const { showToast } = useToast();
  const router = useRouter();
  const isArabic = locale === "ar";

  const storesQuery = useCashbackStoresQuery({
    page: pageStores,
    per_page: 12,
    search: search || undefined,
    sort,
    country_id: selectedCountryId || undefined,
  });
  const offersQuery = useCashbackOffersQuery({
    page: pageOffers,
    per_page: 9,
    search: search || undefined,
    country_id: selectedCountryId || undefined,
  });
  const historyQuery = useCashbackHistoryQuery({ page: pageHistory, per_page: 8 }, isAuthenticated);
  const summaryQuery = useCashbackSummaryQuery(isAuthenticated);
  const activateMutation = useActivateCashbackMutation();
  const categoriesQuery = useCategoriesQuery({ per_page: 80, country_id: selectedCountryId || undefined });

  const categories = useMemo(() => categoriesQuery.data?.items || [], [categoriesQuery.data?.items]);

  const handleActivate = async (offerId: number, storeId: number) => {
    if (!isAuthenticated) {
      showToast({
        type: "info",
        title: isArabic ? "يرجى تسجيل الدخول أولًا" : "Please login first",
        description: isArabic ? "سجّل الدخول لتفعيل الكاش باك." : "Login to activate cashback.",
      });
      router.push("/login");
      return;
    }

    try {
      setActivatingOfferId(offerId);
      const result = await activateMutation.mutateAsync({ storeId, cashbackOfferId: offerId });
      showToast({
        type: "success",
        title: isArabic ? "تم تفعيل الكاش باك" : "Cashback activated",
      });
      await historyQuery.refetch();
      await summaryQuery.refetch();

      if (result.redirect_url) {
        window.open(result.redirect_url, "_blank", "noopener,noreferrer");
      }
    } catch (error) {
      showToast({
        type: "error",
        title: isArabic ? "فشل التفعيل" : "Activation failed",
        description: getApiErrorMessage(error),
      });
    } finally {
      setActivatingOfferId(null);
    }
  };

  return (
    <div>
      <MainHeader />
      <main className="container-shell section-space space-y-4">
        <PageHero
          title={isArabic ? "عروض الكاش باك" : "Cashback Offers"}
          subtitle={isArabic ? "استرد جزءًا من قيمة مشترياتك عند التسوق من المتاجر الشريكة" : "Get part of your purchase amount back from partner stores"}
        />

        <div className="grid grid-cols-1 gap-4 lg:grid-cols-[260px_1fr]">
          <CategorySidebar categories={categories} iconMode="compact" />

          <section className="space-y-5">
            <div className="surface-card p-3">
              <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
                <SearchBar value={search} onChange={setSearch} placeholder={isArabic ? "ابحث في عروض الكاش باك" : "Search cashback offers"} />
                <SortDropdown
                  value={sort}
                  onChange={setSort}
                  options={[
                    { value: "sort_order", label: isArabic ? "الترتيب الافتراضي" : "Default order" },
                    { value: "latest", label: isArabic ? "الأحدث" : "Latest" },
                    { value: "featured", label: isArabic ? "المميزة" : "Featured" },
                  ]}
                />
              </div>
            </div>

            <section className="surface-card p-4">
              <SectionHeader title={isArabic ? "متاجر تدعم الكاش باك" : "Cashback Stores"} />
              {storesQuery.isLoading ? (
                <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
                  {Array.from({ length: 6 }).map((_, i) => <Skeleton key={`store-skeleton-${i}`} className="h-20" />)}
                </div>
              ) : storesQuery.data && storesQuery.data.items.length > 0 ? (
                <>
                  <div className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
                    {storesQuery.data.items.map((store) => (
                      <Link key={`cashback-store-${store.id}`} href={`/stores/${store.slug}`}>
                        <StoreCard store={store} />
                      </Link>
                    ))}
                  </div>
                  <Pagination current={storesQuery.data.meta.current_page} last={storesQuery.data.meta.last_page} onChange={setPageStores} />
                </>
              ) : (
                <EmptyState title={isArabic ? "لا توجد متاجر كاش باك" : "No cashback stores"} description={isArabic ? "جرّب بحثًا آخر." : "Try another search."} />
              )}
            </section>

            <section className="surface-card p-4">
              <SectionHeader title={isArabic ? "العروض النشطة" : "Active Offers"} />
              {offersQuery.isLoading ? (
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                  {Array.from({ length: 3 }).map((_, i) => <Skeleton key={`offer-skeleton-${i}`} className="h-40" />)}
                </div>
              ) : offersQuery.data && offersQuery.data.items.length > 0 ? (
                <>
                  <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    {offersQuery.data.items.map((offer) => (
                      <CashbackCard
                        key={`cashback-offer-${offer.id}`}
                        offer={offer}
                        onActivate={offer.store_id ? (payload) => handleActivate(payload.id, payload.store_id) : undefined}
                        activating={activateMutation.isPending && activatingOfferId === offer.id}
                        activateLabel={isArabic ? "تفعيل الكاش باك" : "Activate Cashback"}
                      />
                    ))}
                  </div>
                  <Pagination current={offersQuery.data.meta.current_page} last={offersQuery.data.meta.last_page} onChange={setPageOffers} />
                </>
              ) : (
                <EmptyState title={isArabic ? "لا توجد عروض كاش باك" : "No cashback offers"} description={isArabic ? "حاول لاحقًا." : "Please try again later."} />
              )}
            </section>

            {isAuthenticated ? (
              <section className="surface-card p-4">
                <SectionHeader title={isArabic ? "سجل الكاش باك الخاص بك" : "Your Cashback History"} />
                {summaryQuery.data ? (
                  <div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-4">
                    <div className="rounded-2xl border border-[var(--border)] bg-white p-3">
                      <p className="text-xs text-slate-500">{isArabic ? "رصيد المحفظة" : "Wallet Balance"}</p>
                      <p className="mt-1 text-lg font-black text-slate-900">{summaryQuery.data.wallet_balance}</p>
                    </div>
                    <div className="rounded-2xl border border-[var(--border)] bg-white p-3">
                      <p className="text-xs text-slate-500">{isArabic ? "قيد الانتظار" : "Pending"}</p>
                      <p className="mt-1 text-lg font-black text-amber-600">{summaryQuery.data.pending_amount}</p>
                    </div>
                    <div className="rounded-2xl border border-[var(--border)] bg-white p-3">
                      <p className="text-xs text-slate-500">{isArabic ? "مقبول" : "Approved"}</p>
                      <p className="mt-1 text-lg font-black text-sky-600">{summaryQuery.data.approved_amount}</p>
                    </div>
                    <div className="rounded-2xl border border-[var(--border)] bg-white p-3">
                      <p className="text-xs text-slate-500">{isArabic ? "مدفوع" : "Paid"}</p>
                      <p className="mt-1 text-lg font-black text-emerald-600">{summaryQuery.data.paid_amount}</p>
                    </div>
                  </div>
                ) : null}
                {historyQuery.isLoading ? (
                  <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
                    {Array.from({ length: 4 }).map((_, i) => <Skeleton key={`history-skeleton-${i}`} className="h-20" />)}
                  </div>
                ) : historyQuery.data && historyQuery.data.items.length > 0 ? (
                  <>
                    <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
                      {historyQuery.data.items.map((entry) => (
                        <div key={`cashback-history-${entry.id}`} className="rounded-2xl border border-[var(--border)] bg-white p-3">
                          <p className="text-sm font-bold text-slate-900">
                            {entry.store
                              ? (isArabic ? entry.store.name_ar : entry.store.name_en) || entry.store.name_ar || entry.store.name_en || (isArabic ? "متجر" : "Store")
                              : (isArabic ? "متجر" : "Store")}
                          </p>
                          <p className="mt-1 text-xs text-slate-500">
                            {isArabic ? "الحالة:" : "Status:"} <span className="font-semibold text-slate-700">{entry.status}</span>
                          </p>
                          <p className="mt-1 text-xs text-slate-500">
                            {isArabic ? "القيمة:" : "Amount:"} <span className="font-semibold text-slate-700">{entry.amount}</span>
                          </p>
                          <p className="mt-1 text-xs text-slate-500">
                            {isArabic ? "التاريخ:" : "Date:"}{" "}
                            <span className="font-semibold text-slate-700">{new Date(entry.created_at).toLocaleString(isArabic ? "ar" : "en-US")}</span>
                          </p>
                        </div>
                      ))}
                    </div>
                    <Pagination current={historyQuery.data.meta.current_page} last={historyQuery.data.meta.last_page} onChange={setPageHistory} />
                  </>
                ) : (
                  <EmptyState
                    title={isArabic ? "لا يوجد سجل كاش باك بعد" : "No cashback history yet"}
                    description={isArabic ? "قم بتفعيل عرض كاش باك ليظهر هنا." : "Activate an offer and it will appear here."}
                  />
                )}
              </section>
            ) : (
              <section className="surface-card p-4">
                <EmptyState
                  title={isArabic ? "سجل الكاش باك يحتاج تسجيل الدخول" : "Cashback history requires login"}
                  description={isArabic ? "سجل الدخول لمتابعة حالة عمليات الكاش باك الخاصة بك." : "Login to view your cashback history."}
                />
              </section>
            )}
          </section>
        </div>
      </main>
      <MainFooter />
    </div>
  );
}
