"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 } from "@/modules/loyalty/design-system";

export default function RenewalRulesPage() {
  const { tenantId } = useTenantId();
  const q = useQuery({
    queryKey: ["loyalty", tenantId, "tiers-rules"],
    queryFn: () => loyaltyApi.tiers.list(tenantId!, { page: 1, page_size: 500 }),
    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="قوانین سطح از tier.rules خوانده می‌شود." />
      <LoyaltyTablePage
        title="سطوح"
        columns={[
          { key: "code", header: "کد" },
          { key: "name", header: "نام" },
          { key: "min_points", header: "حداقل امتیاز" },
          {
            key: "rules",
            header: "rules",
            render: (r) => <code className="text-xs">{JSON.stringify(r.rules ?? {})}</code>,
          },
        ]}
        rows={(q.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="سطحی تعریف نشده" />}
      />
    </div>
  );
}
