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

const schema = z.object({
  name: z.string().min(1, "نام الزامی است"),
  legal_name: z.string().optional(),
  email: z.string().email().optional().or(z.literal("")),
  phone: z.string().optional(),
  website: z.string().optional(),
  kind: z.enum(["company", "account", "partner", "vendor"]).default("company"),
  status: z.enum(["active", "inactive", "prospect", "archived"]).default("active"),
  description: z.string().optional(),
});

export default createCrmListPage<Organization>({
  title: "شرکت‌ها",
  description: "سازمان‌ها و حساب‌های فروش B2B.",
  breadcrumb: "شرکت‌ها",
  resourceKey: "organizations",
  createSchema: schema,
  editSchema: schema.partial(),
  createDefaults: {
    name: "",
    legal_name: "",
    email: "",
    phone: "",
    website: "",
    kind: "company",
    status: "active",
    description: "",
  },
  fields: [
    { name: "name", label: "نام" },
    { name: "legal_name", label: "نام حقوقی" },
    { name: "email", label: "ایمیل", type: "email" },
    { name: "phone", label: "تلفن", type: "tel" },
    { name: "website", label: "وب‌سایت" },
    {
      name: "kind",
      label: "نوع",
      type: "select",
      options: [
        { value: "company", label: "شرکت" },
        { value: "account", label: "حساب" },
        { value: "partner", label: "شریک" },
        { value: "vendor", label: "تأمین‌کننده" },
      ],
    },
    {
      name: "status",
      label: "وضعیت",
      type: "select",
      editOnly: true,
      options: [
        { value: "active", label: "فعال" },
        { value: "inactive", label: "غیرفعال" },
        { value: "prospect", label: "بالقوه" },
        { value: "archived", label: "آرشیو" },
      ],
    },
    { name: "description", label: "توضیحات", type: "textarea" },
  ],
  columns: [
    { key: "organization_number", header: "شماره" },
    { key: "name", header: "نام" },
    { key: "email", header: "ایمیل" },
    { key: "phone", header: "تلفن" },
    {
      key: "status",
      header: "وضعیت",
      render: (r) => <CrmStatusChip status={r.status} domain="organization" />,
    },
  ],
  list: (tid) => crmApi.organizations.list(tid, { page: 1, page_size: 500 }),
  create: (tid, d) => crmApi.organizations.create(tid, d),
  update: (tid, id, d) => crmApi.organizations.update(tid, id, d),
  remove: (tid, id) => crmApi.organizations.delete(tid, id),
  exportColumns: ["organization_number", "name", "email", "phone", "status"],
  filterDeleted: true,
});
