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

export default function Page() {
  const { tenantId } = useTenantId();
  const q = useQuery({
    queryKey: ["loyalty", tenantId, "dash-campaign-performance"],
    queryFn: async () => {
      const [members, campaigns, rewards, wallets] = await Promise.all([
        loyaltyApi.members.list(tenantId!, { page: 1, page_size: 500 }),
        loyaltyApi.campaigns.list(tenantId!, { page: 1, page_size: 500 }),
        loyaltyApi.rewards.list(tenantId!, { page: 1, page_size: 500 }),
        loyaltyApi.wallets.list(tenantId!, { page: 1, page_size: 500 }),
      ]);
      return {
        members: members.length,
        activeMembers: members.filter((m) => m.status === "active").length,
        churned: members.filter((m) => m.status === "cancelled" || m.status === "expired").length,
        campaigns: campaigns.length,
        activeCampaigns: campaigns.filter((c) => c.status === "active").length,
        rewards: rewards.length,
        redeemed: rewards.reduce((s, r) => s + (r.redeemed_count || 0), 0),
        wallets: wallets.length,
      };
    },
    enabled: !!tenantId,
  });
  if (!tenantId || q.isLoading) return <LoyaltyPageLoader />;
  if (q.error) return <LoyaltyPageError error={q.error} onRetry={() => q.refetch()} />;
  const c = q.data!;
  if (c.members === 0 && c.campaigns === 0)
    return (
      <div>
        <LoyaltyBreadcrumbs items={[{ label: "عملکرد کمپین" }]} />
        <PageHeader title="عملکرد کمپین" description="تعداد کمپین بر اساس وضعیت." />
        <EmptyState title="داده‌ای برای تحلیل نیست" />
      </div>
    );
  return (
    <div className="space-y-6">
      <LoyaltyBreadcrumbs items={[{ label: "عملکرد کمپین" }]} />
      <PageHeader title="عملکرد کمپین" description="تعداد کمپین بر اساس وضعیت." />
      <LoyaltyStatGrid
        stats={[
          { label: "اعضا", value: c.members },
          { label: "فعال", value: c.activeMembers },
          { label: "خروجی", value: c.churned },
          { label: "کمپین فعال", value: c.activeCampaigns },
          { label: "پاداش مصرف‌شده", value: c.redeemed },
          { label: "کیف پول", value: c.wallets },
        ]}
      />
    </div>
  );
}
