"use client";

import { Users } from "lucide-react";
import { BrapiEntityPage } from "@/components/brapi/BrapiEntityPage";
import { createPerson, deletePerson, listPersons, updatePerson } from "@/services/dictionaryService";

const loadPersonRows = async () => listPersons() as unknown as Record<string, unknown>[];

const emptyToNull = (value: unknown) => {
  const normalized = String(value ?? "").trim();
  return normalized ? normalized : null;
};

const normalizePersonPayload = (payload: Record<string, unknown>) => ({
  firstName: emptyToNull(payload.firstName),
  middleName: emptyToNull(payload.middleName),
  lastName: emptyToNull(payload.lastName),
  emailAddress: emptyToNull(payload.emailAddress),
  phoneNumber: emptyToNull(payload.phoneNumber),
  instituteName: emptyToNull(payload.instituteName),
  mailingAddress: emptyToNull(payload.mailingAddress),
  description: emptyToNull(payload.description),
  userID: emptyToNull(payload.userID),
});

const createPersonRow = async (payload: Record<string, unknown>) =>
  createPerson(normalizePersonPayload(payload)) as unknown as Record<string, unknown>;

const updatePersonRow = async (id: string, payload: Record<string, unknown>) =>
  updatePerson(id, normalizePersonPayload(payload)) as unknown as Record<string, unknown>;

export default function PersonDictionaryPage() {
  return (
    <BrapiEntityPage
      icon={Users}
      iconBg="bg-gradient-to-br from-blue-500 to-indigo-600"
      title="Person 人员"
      description="维护项目负责人、联系人、录入人员等人员档案"
      addLabel="新增人员"
      columns={[
        { key: "personDbId", label: "Person DbId" },
        { key: "firstName", label: "名" },
        { key: "lastName", label: "姓" },
        { key: "emailAddress", label: "邮箱" },
        { key: "phoneNumber", label: "电话" },
        { key: "instituteName", label: "机构" },
        { key: "userID", label: "User ID" },
      ]}
      fields={[
        { key: "firstName", label: "名 (First Name)", type: "text", required: true },
        { key: "middleName", label: "中间名 (Middle Name)", type: "text" },
        { key: "lastName", label: "姓 (Last Name)", type: "text", required: true },
        { key: "emailAddress", label: "邮箱", type: "text", required: true, placeholder: "xxx@example.com" },
        { key: "phoneNumber", label: "电话", type: "text" },
        { key: "userID", label: "User ID", type: "text", placeholder: "BrAPI userID，可选" },
        { key: "instituteName", label: "所属机构", type: "text", placeholder: "如 中国农业科学院", colSpan: 2 },
        { key: "mailingAddress", label: "通讯地址", type: "text", colSpan: 2 },
        { key: "description", label: "说明", type: "textarea", placeholder: "人员角色、职责或备注" },
      ]}
      data={[]}
      stats={[{ label: "/brapi/v2/people", value: "BrAPI", className: "bg-blue-50 text-blue-700 dark:bg-blue-400/10 dark:text-blue-200" }]}
      loadData={loadPersonRows}
      createRecord={createPersonRow}
      updateRecord={updatePersonRow}
      deleteRecord={deletePerson}
    />
  );
}
