import { z } from "zod";
import { loyaltyApi } from "@/modules/loyalty/services/loyalty-api";
import { createLoyaltyListPage } from "@/modules/loyalty/components/LoyaltyListCrudPage";
import { LoyaltyStatusChip } from "@/modules/loyalty/design-system";
import type { ReferralProgram } from "@/modules/loyalty/types";

const createSchema = z.object({
  program_id: z.string().uuid(),
  code: z.string().min(1),
  name: z.string().min(1),
  status: z.enum(["draft", "active", "inactive"]).default("draft"),
  referrer_bonus_points: z.coerce.number().default(0),
  referee_bonus_points: z.coerce.number().default(0),
  max_referrals_per_member: z.coerce.number().optional(),
});
const editSchema = createSchema.partial().omit({ program_id: true, code: true });

export default createLoyaltyListPage<ReferralProgram>({
  title: "برنامه‌های معرفی",
  description: "پاداش معرف و معرفی‌شونده.",
  breadcrumb: "برنامه معرفی",
  resourceKey: "referral-programs",
  createSchema,
  editSchema,
  createDefaults: {
    program_id: "",
    code: "",
    name: "",
    status: "draft",
    referrer_bonus_points: 0,
    referee_bonus_points: 0,
  },
  fields: [
    { name: "program_id", label: "برنامه وفاداری", createOnly: true, required: true },
    { name: "code", label: "کد", createOnly: true, required: true },
    { name: "name", label: "نام", required: true },
    {
      name: "status",
      label: "وضعیت",
      type: "select",
      options: [
        { value: "draft", label: "پیش‌نویس" },
        { value: "active", label: "فعال" },
        { value: "inactive", label: "غیرفعال" },
      ],
    },
    { name: "referrer_bonus_points", label: "پاداش معرف", type: "number" },
    { name: "referee_bonus_points", label: "پاداش معرفی‌شونده", type: "number" },
  ],
  columns: [
    { key: "code", header: "کد" },
    { key: "name", header: "نام" },
    { key: "referrer_bonus_points", header: "معرف" },
    { key: "referee_bonus_points", header: "معرفی‌شونده" },
    {
      key: "status",
      header: "وضعیت",
      render: (r) => <LoyaltyStatusChip status={r.status} domain="referral_program" />,
    },
  ],
  list: async (tid) => {
    const page = await loyaltyApi.referralPrograms.list(tid, { page: 1, page_size: 500 });
    return ("items" in page ? page.items : page) as ReferralProgram[];
  },
  create: (tid, d) => loyaltyApi.referralPrograms.create(tid, d),
  update: (tid, id, d) => loyaltyApi.referralPrograms.update(tid, id, d),
  remove: (tid, id) => loyaltyApi.referralPrograms.delete(tid, id),
  filterDeleted: true,
  exportColumns: ["code", "name", "status", "referrer_bonus_points", "referee_bonus_points"],
});
