"use client";

import { useQuery } from "@tanstack/react-query";
import { PageHeader, EmptyState } from "@/components/ds";
import { loyaltyApi } from "@/modules/loyalty/services/loyalty-api";
import { useTenantId } from "@/hooks/useTenantId";
import { LoyaltyBreadcrumbs } from "@/modules/loyalty/components/LoyaltyBreadcrumbs";
import { LoyaltyPageLoader, LoyaltyPageError } from "@/modules/loyalty/pages/shared";
import { LoyaltyTablePage, LoyaltyStatusChip } from "@/modules/loyalty/design-system";

export default function PromotionsPage() {
  const { tenantId } = useTenantId();
  const q = useQuery({
    queryKey: ["loyalty", tenantId, "promotions"],
    queryFn: async () => {
      const all = await loyaltyApi.campaigns.list(tenantId!, { page: 1, page_size: 500 });
      return all.filter((c) => c.status === "active" || c.status === "scheduled");
    },
    enabled: !!tenantId,
  });
  if (!tenantId || q.isLoading) return <LoyaltyPageLoader />;
  if (q.error) return <LoyaltyPageError error={q.error} onRetry={() => q.refetch()} />;
  return (
    <div>
      <LoyaltyBreadcrumbs items={[{ label: "تبلیغات فعال" }]} />
      <PageHeader title="تبلیغات فعال" description="کمپین‌های active/scheduled از API واقعی." />
      <LoyaltyTablePage
        title="کمپین‌های فعال"
        columns={[
          { key: "code", header: "کد" },
          { key: "name", header: "نام" },
          {
            key: "status",
            header: "وضعیت",
            render: (r) => <LoyaltyStatusChip status={String(r.status)} domain="campaign" />,
          },
        ]}
        rows={(q.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="کمپین فعالی نیست" />}
      />
    </div>
  );
}
