"use client";

import { useQuery } from "@tanstack/react-query";
import { PageHeader } 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 { LoyaltyStatGrid } from "@/modules/loyalty/design-system";

export default function MemberDashboard() {
  const { tenantId } = useTenantId();
  const q = useQuery({
    queryKey: ["loyalty", tenantId, "member-dash"],
    queryFn: async () => {
      const members = await loyaltyApi.members.list(tenantId!, { page: 1, page_size: 500 });
      const by = (s: string) => members.filter((m) => m.status === s).length;
      return {
        total: members.length,
        active: by("active"),
        pending: by("pending"),
        frozen: by("frozen"),
        cancelled: by("cancelled"),
        expired: by("expired"),
      };
    },
    enabled: !!tenantId,
  });
  if (!tenantId || q.isLoading) return <LoyaltyPageLoader />;
  if (q.error) return <LoyaltyPageError error={q.error} onRetry={() => q.refetch()} />;
  const c = q.data!;
  return (
    <div className="space-y-6">
      <LoyaltyBreadcrumbs items={[{ label: "داشبورد عضو" }]} />
      <PageHeader title="داشبورد اعضا" description="توزیع وضعیت اعضا از API واقعی." />
      <LoyaltyStatGrid
        stats={[
          { label: "کل", value: c.total },
          { label: "فعال", value: c.active },
          { label: "در انتظار", value: c.pending },
          { label: "مسدود", value: c.frozen },
          { label: "لغو", value: c.cancelled },
          { label: "منقضی", value: c.expired },
        ]}
      />
    </div>
  );
}
