"use client";

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 { MembershipTier } from "@/modules/loyalty/types";

const createSchema = z.object({
  program_id: z.string().uuid("شناسه برنامه نامعتبر"),
  code: z.string().min(1),
  name: z.string().min(1),
  description: z.string().optional(),
  rank: z.coerce.number().default(0),
  min_points: z.coerce.number().default(0),
  status: z.enum(["active", "inactive"]).default("active"),
});

const editSchema = createSchema.partial().omit({ program_id: true, code: true });

export default createLoyaltyListPage<MembershipTier>({
  title: "سطوح عضویت",
  description: "تعریف سطوح و حداقل امتیاز برای ارتقا.",
  breadcrumb: "سطوح",
  resourceKey: "tiers",
  createSchema,
  editSchema,
  createDefaults: {
    program_id: "",
    code: "",
    name: "",
    description: "",
    rank: 0,
    min_points: 0,
    status: "active",
  },
  fields: [
    { name: "program_id", label: "شناسه برنامه", required: true, createOnly: true },
    { name: "code", label: "کد", required: true, createOnly: true },
    { name: "name", label: "نام", required: true },
    { name: "description", label: "توضیحات", type: "textarea" },
    { name: "rank", label: "رتبه", type: "number" },
    { name: "min_points", label: "حداقل امتیاز", type: "number" },
    {
      name: "status",
      label: "وضعیت",
      type: "select",
      options: [
        { value: "active", label: "فعال" },
        { value: "inactive", label: "غیرفعال" },
      ],
    },
  ],
  columns: [
    { key: "code", header: "کد" },
    { key: "name", header: "نام" },
    { key: "rank", header: "رتبه" },
    { key: "min_points", header: "حداقل امتیاز" },
    {
      key: "status",
      header: "وضعیت",
      render: (r) => <LoyaltyStatusChip status={r.status} domain="tier" />,
    },
  ],
  list: (tid) => loyaltyApi.tiers.list(tid, { page: 1, page_size: 500 }),
  create: (tid, d) => loyaltyApi.tiers.create(tid, d),
  update: (tid, id, d) => loyaltyApi.tiers.update(tid, id, d),
  remove: (tid, id) => loyaltyApi.tiers.delete(tid, id),
  filterDeleted: true,
  exportColumns: ["code", "name", "rank", "min_points", "status", "program_id"],
});
