"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Users, X, Clock, CheckCircle2, XCircle } from "lucide-react";
import { cn } from "@open-mercato/shared/lib/utils";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Button } from "@open-mercato/ui/primitives/button";
import { Checkbox } from "@open-mercato/ui/primitives/checkbox";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { Popover, PopoverContent, PopoverTrigger } from "@open-mercato/ui/primitives/popover";
import { SearchInput } from "@open-mercato/ui/primitives/search-input";
import { fetchAssignableStaffMembersPage } from "../assignableStaff.js";
import { isVisible, getFieldLabel } from "./fieldConfig.js";
import { PARTICIPANT_COLORS } from "./useScheduleFormState.js";
function ParticipantSearchPopover({
  existingIds,
  onAdd,
  onAddMany,
  t
}) {
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState("");
  const [results, setResults] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [totalPages, setTotalPages] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  const [loadError, setLoadError] = React.useState(null);
  const selectableResults = React.useMemo(
    () => results.filter((result) => !existingIds.has(result.userId)),
    [existingIds, results]
  );
  React.useEffect(() => {
    if (!open) return;
    const controller = new AbortController();
    setLoading(true);
    fetchAssignableStaffMembersPage(query, { page, pageSize: 20, signal: controller.signal }).then((result) => {
      const members = result.items;
      const nextResults = members.map((member) => ({
        userId: member.userId,
        name: member.displayName,
        email: member.email ?? ""
      }));
      setResults((current) => {
        if (page <= 1) return nextResults;
        const merged = new Map(current.map((entry) => [entry.userId, entry]));
        nextResults.forEach((entry) => merged.set(entry.userId, entry));
        return Array.from(merged.values());
      });
      setTotalPages(result.total > 0 ? Math.max(1, Math.ceil(result.total / result.pageSize)) : 1);
      setLoadError(null);
    }).catch(() => {
      setResults([]);
      setLoadError(
        t(
          "customers.assignableStaff.loadError",
          "Unable to load team members. Check your permissions and try again."
        )
      );
    }).finally(() => setLoading(false));
    return () => controller.abort();
  }, [open, page, query, t]);
  React.useEffect(() => {
    if (!open) return;
    setPage(1);
  }, [open, query]);
  return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(Button, { type: "button", variant: "ghost", size: "sm", className: "h-auto inline-flex items-center gap-1.5 rounded-full border border-status-success-border bg-status-success-bg px-2.5 py-1.5 text-xs font-semibold text-foreground", children: [
      /* @__PURE__ */ jsx(Users, { className: "size-3" }),
      t("customers.schedule.addParticipant", "Add participant")
    ] }) }),
    /* @__PURE__ */ jsxs(PopoverContent, { align: "start", className: "w-72 p-2", children: [
      /* @__PURE__ */ jsx(
        SearchInput,
        {
          value: query,
          onChange: setQuery,
          placeholder: t("customers.schedule.searchParticipant", "Search team members..."),
          className: "mb-2",
          autoFocus: true
        }
      ),
      selectableResults.length ? /* @__PURE__ */ jsx("div", { className: "mb-2", children: /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          className: "w-full",
          onClick: () => {
            onAddMany(
              selectableResults.map((participant, index) => ({
                userId: participant.userId,
                name: participant.name,
                email: participant.email,
                color: PARTICIPANT_COLORS[(existingIds.size + index) % PARTICIPANT_COLORS.length]
              }))
            );
            setOpen(false);
            setQuery("");
          },
          children: t("customers.schedule.addVisibleParticipants", "Add all visible")
        }
      ) }) : null,
      /* @__PURE__ */ jsxs("div", { className: "max-h-48 overflow-y-auto space-y-0.5", children: [
        loading && /* @__PURE__ */ jsx("p", { className: "px-2 py-3 text-xs text-muted-foreground text-center", children: t("customers.schedule.searching", "Searching...") }),
        !loading && loadError && /* @__PURE__ */ jsx("p", { className: "px-2 py-3 text-xs text-destructive text-center", children: loadError }),
        !loading && !loadError && results.length === 0 && /* @__PURE__ */ jsx("p", { className: "px-2 py-3 text-xs text-muted-foreground text-center", children: t("customers.schedule.noResults", "No results") }),
        results.map((r) => {
          const alreadyAdded = existingIds.has(r.userId);
          return /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              disabled: alreadyAdded,
              onClick: () => {
                onAdd({ userId: r.userId, name: r.name, email: r.email, color: PARTICIPANT_COLORS[existingIds.size % PARTICIPANT_COLORS.length] });
                setOpen(false);
                setQuery("");
              },
              className: cn(
                "h-auto flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",
                alreadyAdded ? "opacity-40 cursor-default" : "hover:bg-accent cursor-pointer"
              ),
              children: [
                /* @__PURE__ */ jsx("span", { className: "inline-flex size-6 items-center justify-center rounded-full bg-muted text-xs font-bold shrink-0", children: r.name.charAt(0).toUpperCase() }),
                /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate", children: r.name }),
                r.email && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground truncate", children: r.email })
              ]
            },
            r.userId
          );
        }),
        !loading && !loadError && page < totalPages ? /* @__PURE__ */ jsx("div", { className: "px-2 py-2", children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", className: "w-full", onClick: () => setPage((current) => current + 1), children: t("customers.schedule.loadMore", "Load more") }) }) : null
      ] })
    ] })
  ] });
}
function ParticipantsField({
  visible,
  activityType,
  participants,
  setParticipants,
  removeParticipant,
  guestPermissions,
  setGuestPermissions
}) {
  const t = useT();
  if (!isVisible(activityType, "participants")) return null;
  const sectionLabel = getFieldLabel(
    activityType,
    "participants",
    t,
    "customers.schedule.participants",
    "Participants"
  );
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx("label", { className: "text-overline font-semibold uppercase text-muted-foreground tracking-wider", children: sectionLabel }),
    /* @__PURE__ */ jsxs("div", { className: "mt-2.5 flex flex-wrap content-center items-center gap-2 rounded-lg border border-border bg-background px-3 py-2.5", children: [
      participants.map((p) => /* @__PURE__ */ jsxs("div", { className: "inline-flex items-center gap-1.5 rounded-full border border-border bg-muted px-2.5 py-1.5", children: [
        /* @__PURE__ */ jsx("span", { className: cn("inline-flex size-5 items-center justify-center rounded-full text-xs font-bold text-white", p.color ?? "bg-primary"), children: p.name.charAt(0).toUpperCase() }),
        /* @__PURE__ */ jsx("span", { className: "text-xs text-foreground", children: p.name }),
        /* @__PURE__ */ jsx(IconButton, { type: "button", variant: "ghost", size: "sm", onClick: () => removeParticipant(p.userId), className: "h-auto text-muted-foreground hover:text-foreground p-0", "aria-label": t("customers.schedule.removeParticipant", "Remove participant"), children: /* @__PURE__ */ jsx(X, { className: "size-3" }) })
      ] }, p.userId)),
      /* @__PURE__ */ jsx(
        ParticipantSearchPopover,
        {
          existingIds: new Set(participants.map((p) => p.userId)),
          onAdd: (p) => setParticipants((prev) => [...prev, { ...p, status: "pending" }]),
          onAddMany: (nextParticipants) => {
            setParticipants((prev) => [
              ...prev,
              ...nextParticipants.map((participant) => ({ ...participant, status: "pending" }))
            ]);
          },
          t
        }
      )
    ] }),
    participants.length > 0 && /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-center gap-x-[16px] gap-y-[6px] text-xs", children: [
      /* @__PURE__ */ jsx("span", { className: "font-medium text-muted-foreground", children: t("customers.schedule.guestPermissions", "Guest permissions:") }),
      /* @__PURE__ */ jsxs("label", { htmlFor: "guest-perm-invite", className: "flex items-center gap-1.5 cursor-pointer", children: [
        /* @__PURE__ */ jsx(Checkbox, { id: "guest-perm-invite", checked: guestPermissions.canInviteOthers, onCheckedChange: (checked) => setGuestPermissions((p) => ({ ...p, canInviteOthers: checked === true })) }),
        t("customers.schedule.guestPerm.invite", "Invite others")
      ] }),
      /* @__PURE__ */ jsxs("label", { htmlFor: "guest-perm-modify", className: "flex items-center gap-1.5 cursor-pointer", children: [
        /* @__PURE__ */ jsx(Checkbox, { id: "guest-perm-modify", checked: guestPermissions.canModify, onCheckedChange: (checked) => setGuestPermissions((p) => ({ ...p, canModify: checked === true })) }),
        t("customers.schedule.guestPerm.modify", "Modify")
      ] }),
      /* @__PURE__ */ jsxs("label", { htmlFor: "guest-perm-see-list", className: "flex items-center gap-1.5 cursor-pointer", children: [
        /* @__PURE__ */ jsx(Checkbox, { id: "guest-perm-see-list", checked: guestPermissions.canSeeList, onCheckedChange: (checked) => setGuestPermissions((p) => ({ ...p, canSeeList: checked === true })) }),
        t("customers.schedule.guestPerm.seeList", "See list")
      ] })
    ] }),
    participants.length > 0 && (() => {
      const accepted = participants.filter((p) => p.status === "accepted").length;
      const pending = participants.filter((p) => !p.status || p.status === "pending").length;
      const declined = participants.filter((p) => p.status === "declined").length;
      if (accepted === 0 && pending === 0 && declined === 0) return null;
      return /* @__PURE__ */ jsxs("div", { className: "mt-2 flex items-center gap-3 text-xs", children: [
        /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("customers.schedule.rsvp.label", "Responses:") }),
        accepted > 0 && /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 font-medium text-status-success-text", children: [
          /* @__PURE__ */ jsx(CheckCircle2, { className: "size-3.5" }),
          " ",
          accepted,
          " ",
          t("customers.schedule.rsvp.accepted", "tak")
        ] }),
        pending > 0 && /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 font-medium text-status-warning-text", children: [
          /* @__PURE__ */ jsx(Clock, { className: "size-3.5" }),
          " ",
          pending,
          " ",
          t("customers.schedule.rsvp.pending", "czeka")
        ] }),
        declined > 0 && /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1 font-medium text-status-error-text", children: [
          /* @__PURE__ */ jsx(XCircle, { className: "size-3.5" }),
          " ",
          declined,
          " ",
          t("customers.schedule.rsvp.declined", "nie")
        ] })
      ] });
    })()
  ] });
}
export {
  ParticipantsField
};
//# sourceMappingURL=ParticipantsField.js.map
