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

const createSchema = z.object({
  program_id: z.string().uuid(),
  member_id: z.string().uuid(),
  account_number: z.string().optional(),
  currency_name: z.string().default("points"),
  status: z.enum(["open", "frozen", "closed"]).default("open"),
});
const editSchema = z.object({
  status: z.enum(["open", "frozen", "closed"]).optional(),
  currency_name: z.string().optional(),
  version: z.coerce.number().optional(),
});

export default createLoyaltyListPage<PointAccount>({
  title: "حساب‌های امتیاز",
  description: "حساب‌های دفترکل امتیاز اعضا.",
  breadcrumb: "حساب امتیاز",
  resourceKey: "point-accounts",
  createSchema,
  editSchema,
  createDefaults: {
    program_id: "",
    member_id: "",
    account_number: "",
    currency_name: "points",
    status: "open",
  },
  fields: [
    { name: "program_id", label: "برنامه", createOnly: true, required: true },
    { name: "member_id", label: "عضو", createOnly: true, required: true },
    { name: "account_number", label: "شماره حساب", createOnly: true },
    { name: "currency_name", label: "واحد" },
    {
      name: "status",
      label: "وضعیت",
      type: "select",
      options: [
        { value: "open", label: "باز" },
        { value: "frozen", label: "مسدود" },
        { value: "closed", label: "بسته" },
      ],
    },
  ],
  columns: [
    { key: "account_number", header: "شماره" },
    { key: "member_id", header: "عضو" },
    { key: "currency_name", header: "واحد" },
    {
      key: "status",
      header: "وضعیت",
      render: (r) => <LoyaltyStatusChip status={r.status} domain="point_account" />,
    },
  ],
  list: (tid) => loyaltyApi.pointAccounts.list(tid, { page: 1, page_size: 500 }),
  create: (tid, d) => loyaltyApi.pointAccounts.create(tid, d),
  update: (tid, id, d) => loyaltyApi.pointAccounts.update(tid, id, d),
  remove: (tid, id) => loyaltyApi.pointAccounts.delete(tid, id),
  filterDeleted: true,
  exportColumns: ["account_number", "member_id", "program_id", "status", "currency_name"],
});
