"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useRouter } from "next/navigation";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { normalizeCustomFieldValues } from "@open-mercato/shared/lib/custom-fields/normalize";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { LookupSelect } from "@open-mercato/ui/backend/inputs";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { AttachmentsSection, TagsSection } from "@open-mercato/ui/backend/detail";
import { E } from "../../../generated/entities.ids.generated.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { Plus } from "lucide-react";
const DEFAULT_PAGE_SIZE = 100;
const normalizeCustomFieldSubmitValue = (value) => {
  const normalized = normalizeCustomFieldValues({ value });
  return normalized.value;
};
const buildTeamMemberPayload = (values, options = {}) => {
  const roleIds = Array.isArray(values.roleIds) ? values.roleIds.filter((item) => typeof item === "string") : [];
  const tags = Array.isArray(values.tags) ? values.tags.filter((item) => typeof item === "string" && item.trim().length > 0) : null;
  const customFields = collectCustomFieldValues(values, { transform: normalizeCustomFieldSubmitValue });
  return {
    ...options.id ? { id: options.id } : {},
    teamId: values.teamId ? String(values.teamId) : null,
    userId: values.userId ? String(values.userId) : null,
    displayName: typeof values.displayName === "string" ? values.displayName : "",
    description: typeof values.description === "string" && values.description.trim().length ? values.description : null,
    roleIds,
    ...tags ? { tags } : {},
    isActive: values.isActive ?? true,
    ...Object.keys(customFields).length ? { customFields } : {}
  };
};
function TeamMemberForm(props) {
  const {
    title,
    submitLabel,
    backHref,
    cancelHref,
    embedded = false,
    initialValues,
    onSubmit,
    onDelete,
    isLoading,
    loadingMessage,
    tagsSection
  } = props;
  const translate = useT();
  const recordId = typeof initialValues?.id === "string" ? initialValues.id : null;
  const router = useRouter();
  const scopeVersion = useOrganizationScopeVersion();
  const [roles, setRoles] = React.useState([]);
  const [selectedTeamId, setSelectedTeamId] = React.useState(null);
  const [userOptions, setUserOptions] = React.useState([]);
  const [teamOptions, setTeamOptions] = React.useState([]);
  const [roleSearch, setRoleSearch] = React.useState("");
  const resolvedTeamId = typeof initialValues.teamId === "string" && initialValues.teamId.trim().length ? initialValues.teamId : null;
  const resolvedUserId = typeof initialValues.userId === "string" && initialValues.userId.trim().length ? initialValues.userId : null;
  React.useEffect(() => {
    setSelectedTeamId(resolvedTeamId);
  }, [resolvedTeamId]);
  React.useEffect(() => {
    let cancelled = false;
    async function loadRoles() {
      try {
        const params = new URLSearchParams({ page: "1", pageSize: String(DEFAULT_PAGE_SIZE) });
        const call = await apiCall(`/api/staff/team-roles?${params.toString()}`);
        const items = Array.isArray(call.result?.items) ? call.result.items : [];
        const nextRoles = items.map(mapTeamRole).filter((role) => role !== null);
        if (!cancelled) setRoles(nextRoles);
      } catch {
        if (!cancelled) setRoles([]);
      }
    }
    loadRoles();
    return () => {
      cancelled = true;
    };
  }, [scopeVersion]);
  React.useEffect(() => {
    let cancelled = false;
    async function loadTeams() {
      try {
        const params = new URLSearchParams({ page: "1", pageSize: "100" });
        const call = await apiCall(`/api/staff/teams?${params.toString()}`);
        const items = Array.isArray(call.result?.items) ? call.result.items : [];
        const options = items.map((team) => {
          const id = typeof team.id === "string" ? team.id : null;
          const name = typeof team.name === "string" ? team.name : null;
          if (!id || !name) return null;
          return { value: id, label: name };
        }).filter((entry) => entry !== null);
        if (!cancelled) setTeamOptions(options);
      } catch {
        if (!cancelled) setTeamOptions([]);
      }
    }
    loadTeams();
    return () => {
      cancelled = true;
    };
  }, [scopeVersion]);
  React.useEffect(() => {
    if (!resolvedTeamId) return;
    if (teamOptions.some((option) => option.value === resolvedTeamId)) return;
    const selectedTeamId2 = resolvedTeamId;
    let cancelled = false;
    async function loadSelectedTeam() {
      try {
        const call = await apiCall(`/api/staff/teams?ids=${encodeURIComponent(selectedTeamId2)}&pageSize=1`);
        const entry = Array.isArray(call.result?.items) ? call.result.items[0] : null;
        const entryId = typeof entry?.id === "string" ? entry.id : null;
        const entryName = typeof entry?.name === "string" ? entry.name : null;
        if (!entryId || !entryName) return;
        if (!cancelled) {
          setTeamOptions((prev) => {
            if (prev.some((option) => option.value === entryId)) return prev;
            return [{ value: entryId, label: entryName }, ...prev];
          });
        }
      } catch {
        if (!cancelled) setTeamOptions((prev) => prev);
      }
    }
    loadSelectedTeam();
    return () => {
      cancelled = true;
    };
  }, [resolvedTeamId, teamOptions]);
  React.useEffect(() => {
    if (!resolvedUserId) return;
    const userId = resolvedUserId;
    if (userOptions.some((option) => option.id === resolvedUserId)) return;
    let cancelled = false;
    async function loadSelectedUser() {
      try {
        const call = await apiCall(`/api/auth/users?id=${encodeURIComponent(userId)}`);
        const entry = Array.isArray(call.result?.items) ? call.result.items[0] : null;
        const entryId = typeof entry?.id === "string" ? entry.id : null;
        const entryEmail = typeof entry?.email === "string" ? entry.email : null;
        if (!entryId || !entryEmail) return;
        if (!cancelled) {
          setUserOptions((prev) => {
            if (prev.some((option) => option.id === entryId)) return prev;
            return [{ id: entryId, title: entryEmail, subtitle: entry?.organizationName ?? null }, ...prev];
          });
        }
      } catch {
        if (!cancelled) setUserOptions((prev) => prev);
      }
    }
    loadSelectedUser();
    return () => {
      cancelled = true;
    };
  }, [resolvedUserId, userOptions]);
  const filteredRoles = React.useMemo(
    () => filterRolesByTeam(roles, selectedTeamId),
    [roles, selectedTeamId]
  );
  const roleOptions = React.useMemo(
    () => filteredRoles.map((role) => ({ value: role.id, label: role.name })),
    [filteredRoles]
  );
  const filteredRoleOptions = React.useMemo(() => {
    const query = roleSearch.trim().toLowerCase();
    if (!query) return roleOptions;
    return roleOptions.filter((option) => option.label.toLowerCase().includes(query) || option.value.toLowerCase().includes(query));
  }, [roleOptions, roleSearch]);
  const createRoleHref = React.useMemo(() => {
    const params = new URLSearchParams();
    if (selectedTeamId) params.set("teamId", selectedTeamId);
    const query = params.toString();
    return `/backend/staff/team-roles/create${query ? `?${query}` : ""}`;
  }, [selectedTeamId]);
  const createTeamHref = "/backend/staff/teams/create";
  React.useEffect(() => {
    setRoleSearch("");
  }, [selectedTeamId]);
  const fetchUserOptions = React.useCallback(async (query) => {
    const params = new URLSearchParams({ page: "1", pageSize: "50" });
    if (query && query.trim().length) params.set("search", query.trim());
    const call = await apiCall(`/api/auth/users?${params.toString()}`);
    const items = Array.isArray(call.result?.items) ? call.result.items : [];
    const options = items.map((user) => {
      const id = typeof user?.id === "string" ? user.id : null;
      const email = typeof user?.email === "string" ? user.email : null;
      if (!id || !email) return null;
      return {
        id,
        title: email,
        subtitle: user.organizationName ?? null
      };
    }).filter((option) => option !== null);
    setUserOptions(options);
    return options;
  }, []);
  const fields = React.useMemo(() => {
    const baseFields = [
      {
        id: "userId",
        label: translate("staff.teamMembers.form.fields.user", "User"),
        type: "custom",
        component: ({ value, setValue }) => /* @__PURE__ */ jsx(
          LookupSelect,
          {
            value: typeof value === "string" ? value : null,
            onChange: (next) => setValue(next),
            options: userOptions,
            fetchOptions: fetchUserOptions,
            placeholder: translate("staff.teamMembers.form.fields.user.placeholder", "Select a user"),
            searchPlaceholder: translate("staff.teamMembers.form.fields.user.search", "Search users"),
            emptyLabel: translate("staff.teamMembers.form.fields.user.empty", "No users found"),
            selectedHintLabel: (id) => translate("staff.teamMembers.form.fields.user.selected", "Selected user: {{id}}", { id })
          }
        )
      },
      {
        id: "teamId",
        label: "",
        type: "custom",
        component: ({ value, setValue, setFormValue, values, disabled }) => {
          const currentValue = typeof value === "string" ? value : "";
          const selectedOption = teamOptions.find((option) => option.value === currentValue);
          const optionsKey = teamOptions.map((option) => `${option.value}:${option.label}`).join("\0");
          return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
              /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: translate("staff.teamMembers.form.fields.team", "Team") }),
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  size: "sm",
                  variant: "outline",
                  onClick: () => router.push(createTeamHref),
                  disabled,
                  children: [
                    /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4", "aria-hidden": true }),
                    translate("staff.teamMembers.form.actions.createTeam", "Create new team")
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsxs(
              Select,
              {
                value: currentValue,
                onValueChange: (value2) => {
                  const nextValue = value2 || void 0;
                  const nextTeamId = value2 || null;
                  setValue(nextValue);
                  setSelectedTeamId(nextTeamId);
                  if (!setFormValue) return;
                  const roleIds = Array.isArray(values?.roleIds) ? values?.roleIds.filter((item) => typeof item === "string") : [];
                  const allowedRoleIds = buildAllowedRoleIdSet(roles, nextTeamId);
                  const nextRoleIds = roleIds.filter((roleId) => allowedRoleIds.has(roleId));
                  if (nextRoleIds.length !== roleIds.length) {
                    setFormValue("roleIds", nextRoleIds);
                  }
                },
                disabled,
                children: [
                  /* @__PURE__ */ jsx(SelectTrigger, { "data-crud-focus-target": "", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: translate("ui.forms.select.emptyOption", "\u2014"), children: selectedOption?.label }) }),
                  /* @__PURE__ */ jsx(SelectContent, { children: teamOptions.map((option) => /* @__PURE__ */ jsx(SelectItem, { value: option.value, children: option.label }, option.value)) })
                ]
              },
              `team:${currentValue}:${optionsKey}`
            )
          ] });
        }
      },
      {
        id: "displayName",
        label: translate("staff.teamMembers.form.fields.displayName", "Display name"),
        type: "text",
        required: true
      },
      {
        id: "description",
        label: translate("staff.teamMembers.form.fields.description", "Description"),
        type: "richtext",
        editor: "uiw"
      },
      {
        id: "roleIds",
        label: "",
        type: "custom",
        component: ({ value, setValue, disabled }) => {
          const selectedValues = Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
          return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
              /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: translate("staff.teamMembers.form.fields.roles", "Roles") }),
              /* @__PURE__ */ jsxs(
                Button,
                {
                  type: "button",
                  size: "sm",
                  variant: "outline",
                  onClick: () => router.push(createRoleHref),
                  disabled,
                  children: [
                    /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4", "aria-hidden": true }),
                    translate("staff.teamMembers.form.actions.defineRole", "Define new role")
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ jsx(
              "input",
              {
                className: "w-full h-8 rounded border px-2 text-sm",
                placeholder: translate("ui.forms.listbox.searchPlaceholder", "Search..."),
                value: roleSearch,
                onChange: (event) => setRoleSearch(event.target.value),
                "data-crud-focus-target": "",
                disabled
              }
            ),
            /* @__PURE__ */ jsxs("div", { className: "rounded border max-h-48 overflow-auto divide-y", children: [
              filteredRoleOptions.map((option) => {
                const isSelected = selectedValues.includes(option.value);
                return /* @__PURE__ */ jsx(
                  "button",
                  {
                    type: "button",
                    onClick: () => {
                      const next = new Set(selectedValues);
                      if (isSelected) {
                        next.delete(option.value);
                      } else {
                        next.add(option.value);
                      }
                      setValue(Array.from(next));
                    },
                    className: `w-full text-left px-3 py-2 text-sm hover:bg-muted ${isSelected ? "bg-muted" : ""}`,
                    disabled,
                    children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
                      /* @__PURE__ */ jsx("input", { type: "checkbox", className: "size-4", readOnly: true, checked: isSelected }),
                      /* @__PURE__ */ jsx("span", { children: option.label })
                    ] })
                  },
                  option.value
                );
              }),
              !filteredRoleOptions.length ? /* @__PURE__ */ jsx("div", { className: "px-3 py-2 text-sm text-muted-foreground", children: translate("ui.forms.listbox.noMatches", "No matches") }) : null
            ] })
          ] });
        }
      },
      {
        id: "isActive",
        label: translate("staff.teamMembers.form.fields.active", "Active"),
        type: "checkbox"
      }
    ];
    if (!tagsSection) {
      baseFields.splice(5, 0, {
        id: "tags",
        label: "",
        type: "tags",
        placeholder: translate("staff.teamMembers.form.fields.tags.placeholder", "Add tags")
      });
    }
    return baseFields;
  }, [
    createRoleHref,
    fetchUserOptions,
    filteredRoleOptions,
    roleSearch,
    roles,
    router,
    tagsSection,
    translate,
    teamOptions,
    userOptions
  ]);
  const groups = React.useMemo(() => {
    const baseGroups = [
      {
        id: "details",
        column: 1,
        fields: ["userId", "teamId", "displayName", "description", "roleIds", "isActive"]
      },
      {
        id: "custom",
        title: translate("entities.customFields.title", "Custom Attributes"),
        column: 2,
        kind: "customFields"
      }
    ];
    if (tagsSection) {
      baseGroups.push({
        id: "tags",
        column: 2,
        bare: true,
        component: () => /* @__PURE__ */ jsx(
          TagsSection,
          {
            title: tagsSection.title,
            tags: tagsSection.tags,
            onChange: tagsSection.onChange,
            loadOptions: tagsSection.loadOptions,
            createTag: tagsSection.createTag,
            onSave: tagsSection.onSave,
            labels: tagsSection.labels
          }
        )
      });
    } else {
      baseGroups.splice(1, 0, {
        id: "tags",
        title: translate("staff.teamMembers.form.fields.tags", "Tags"),
        column: 2,
        fields: ["tags"]
      });
    }
    baseGroups.push({
      id: "attachments",
      title: translate("attachments.library.title", "Attachments"),
      column: 1,
      component: () => /* @__PURE__ */ jsx(
        AttachmentsSection,
        {
          entityId: E.staff.staff_team_member,
          recordId,
          showHeader: false
        }
      )
    });
    return baseGroups;
  }, [recordId, tagsSection, translate]);
  return /* @__PURE__ */ jsx(
    CrudForm,
    {
      embedded,
      title,
      backHref,
      cancelHref,
      versionHistory: initialValues.id ? { resourceKind: "staff.teamMember", resourceId: String(initialValues.id) } : void 0,
      submitLabel,
      fields,
      groups,
      entityId: E.staff.staff_team_member,
      initialValues,
      optimisticLockUpdatedAt: initialValues.updatedAt,
      onSubmit,
      onDelete,
      isLoading,
      loadingMessage
    }
  );
}
function mapTeamRole(item) {
  const id = typeof item.id === "string" ? item.id : "";
  if (!id) return null;
  const name = typeof item.name === "string" && item.name.trim().length ? item.name.trim() : id;
  const teamId = typeof item.teamId === "string" ? item.teamId : typeof item.team_id === "string" ? item.team_id : null;
  return { id, name, teamId };
}
function filterRolesByTeam(roles, teamId) {
  if (!teamId) return roles.filter((role) => role.teamId == null);
  return roles.filter((role) => role.teamId == null || role.teamId === teamId);
}
function buildAllowedRoleIdSet(roles, teamId) {
  return new Set(filterRolesByTeam(roles, teamId).map((role) => role.id));
}
export {
  TeamMemberForm,
  buildTeamMemberPayload
};
//# sourceMappingURL=TeamMemberForm.js.map
