import { z } from "zod";
import { crmApi } from "@/modules/crm/services/crm-api";
import { createCrmListPage } from "@/modules/crm/components/CrmListCrudPage";
import { CrmStatusChip } from "@/modules/crm/design-system";
import type { Contact } from "@/modules/crm/types";

const schema = z.object({
  first_name: z.string().min(1, "نام الزامی است"),
  last_name: z.string().min(1, "نام خانوادگی الزامی است"),
  email: z.string().email().optional().or(z.literal("")),
  phone: z.string().optional(),
  job_title: z.string().optional(),
  kind: z.enum(["business", "personal"]).default("business"),
  status: z.enum(["active", "inactive", "archived"]).default("active"),
});

export default createCrmListPage<Contact>({
  title: "مخاطبین",
  description: "دفترچه مخاطبین CRM — اشخاص مرتبط با سازمان‌ها و معاملات.",
  breadcrumb: "مخاطبین",
  resourceKey: "contacts",
  createSchema: schema,
  editSchema: schema.partial(),
  createDefaults: {
    first_name: "",
    last_name: "",
    email: "",
    phone: "",
    job_title: "",
    kind: "business",
    status: "active",
  },
  fields: [
    { name: "first_name", label: "نام" },
    { name: "last_name", label: "نام خانوادگی" },
    { name: "email", label: "ایمیل", type: "email" },
    { name: "phone", label: "تلفن", type: "tel" },
    { name: "job_title", label: "سمت" },
    {
      name: "kind",
      label: "نوع",
      type: "select",
      options: [
        { value: "business", label: "کسب‌وکار" },
        { value: "personal", label: "شخصی" },
      ],
    },
    {
      name: "status",
      label: "وضعیت",
      type: "select",
      editOnly: true,
      options: [
        { value: "active", label: "فعال" },
        { value: "inactive", label: "غیرفعال" },
        { value: "archived", label: "آرشیو" },
      ],
    },
  ],
  columns: [
    { key: "full_name", header: "نام" },
    { key: "email", header: "ایمیل" },
    { key: "phone", header: "تلفن" },
    { key: "job_title", header: "سمت" },
    {
      key: "status",
      header: "وضعیت",
      render: (r) => <CrmStatusChip status={r.status} domain="contact" />,
    },
  ],
  list: (tid) => crmApi.contacts.list(tid, { page: 1, page_size: 500 }),
  create: (tid, d) => crmApi.contacts.create(tid, d),
  update: (tid, id, d) => crmApi.contacts.update(tid, id, d),
  remove: (tid, id) => crmApi.contacts.delete(tid, id),
  exportColumns: ["full_name", "email", "phone", "job_title", "status"],
  filterDeleted: true,
});
