"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Button, 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 CouponsPage() {
  const { tenantId } = useTenantId();
  const qc = useQueryClient();
  const q = useQuery({
    queryKey: ["loyalty", tenantId, "redemptions"],
    queryFn: async () => {
      const page = await loyaltyApi.redemptions.list(tenantId!, { page: 1, page_size: 200 });
      return "items" in page ? page.items : (page as never);
    },
    enabled: !!tenantId,
  });

  const fulfill = useMutation({
    mutationFn: (id: string) => loyaltyApi.redemptions.fulfill(tenantId!, id),
    onSuccess: () => {
      toast.success("تحویل شد");
      qc.invalidateQueries({ queryKey: ["loyalty", tenantId, "redemptions"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  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="کدهای voucher از Redeem واقعی پاداش." />
      <LoyaltyTablePage
        title="بازخریدها"
        columns={[
          { key: "voucher_code", header: "کد" },
          { key: "points_spent", header: "امتیاز" },
          {
            key: "status",
            header: "وضعیت",
            render: (r) => <LoyaltyStatusChip status={String(r.status)} domain="redemption" />,
          },
          { key: "member_id", header: "عضو" },
          {
            key: "actions",
            header: "عملیات",
            searchable: false,
            render: (r) =>
              r.status === "pending" || r.status === "issued" ? (
                <Button size="sm" variant="outline" onClick={() => fulfill.mutate(String(r.id))}>
                  تحویل
                </Button>
              ) : null,
          },
        ]}
        rows={(q.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="کوپنی ثبت نشده" />}
      />
    </div>
  );
}
