"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { createPortal } from "react-dom";
import { Button } from "@open-mercato/ui/primitives/button";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Plus, Search } from "lucide-react";
import { ProjectColorDot } from "./ProjectColorDot.js";
const DROPDOWN_WIDTH = 280;
const DROPDOWN_OFFSET = 4;
function AddRowDropdown({
  assignedProjects,
  visibleProjectIds,
  canCreateProject,
  onAddProject,
  onCreateProject
}) {
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const [search, setSearch] = React.useState("");
  const [position, setPosition] = React.useState(null);
  const triggerRef = React.useRef(null);
  const dropdownRef = React.useRef(null);
  const searchInputRef = React.useRef(null);
  const availableProjects = assignedProjects.filter(
    (project) => !visibleProjectIds.has(project.id)
  );
  const filteredProjects = availableProjects.filter(
    (project) => project.name.toLowerCase().includes(search.toLowerCase())
  );
  React.useLayoutEffect(() => {
    if (!open) return;
    const updatePosition = () => {
      const node = triggerRef.current;
      if (!node) return;
      const rect = node.getBoundingClientRect();
      const left = Math.max(8, Math.min(rect.left, window.innerWidth - DROPDOWN_WIDTH - 8));
      setPosition({ top: rect.bottom + DROPDOWN_OFFSET, left });
    };
    updatePosition();
    window.addEventListener("scroll", updatePosition, true);
    window.addEventListener("resize", updatePosition);
    return () => {
      window.removeEventListener("scroll", updatePosition, true);
      window.removeEventListener("resize", updatePosition);
    };
  }, [open]);
  React.useEffect(() => {
    if (!open) return;
    function handleClickOutside(event) {
      const target = event.target;
      if (triggerRef.current && !triggerRef.current.contains(target) && dropdownRef.current && !dropdownRef.current.contains(target)) {
        setOpen(false);
        setSearch("");
      }
    }
    function handleKeyDown(event) {
      if (event.key === "Escape") {
        setOpen(false);
        setSearch("");
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [open]);
  React.useEffect(() => {
    if (open && searchInputRef.current) {
      searchInputRef.current.focus();
    }
  }, [open]);
  function handleToggle() {
    setOpen((prev) => !prev);
    setSearch("");
  }
  function handleSelectProject(project) {
    onAddProject(project);
    setOpen(false);
    setSearch("");
  }
  function handleCreateProject() {
    onCreateProject();
    setOpen(false);
    setSearch("");
  }
  const dropdown = open && position && typeof document !== "undefined" ? createPortal(
    /* @__PURE__ */ jsxs(
      "div",
      {
        ref: dropdownRef,
        className: "fixed z-50 rounded-lg border bg-popover shadow-lg",
        style: { top: position.top, left: position.left, width: DROPDOWN_WIDTH },
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center border-b px-3", children: [
            /* @__PURE__ */ jsx(Search, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
            /* @__PURE__ */ jsx(
              "input",
              {
                ref: searchInputRef,
                type: "text",
                className: "w-full px-3 py-2 text-sm bg-transparent outline-none placeholder:text-muted-foreground",
                placeholder: t("staff.timesheets.my.addRow.searchPlaceholder", "Search by project"),
                value: search,
                onChange: (event) => setSearch(event.target.value)
              }
            )
          ] }),
          /* @__PURE__ */ jsx("div", { className: "max-h-[200px] overflow-y-auto", children: filteredProjects.length === 0 ? /* @__PURE__ */ jsx("div", { className: "px-3 py-4 text-sm text-muted-foreground text-center", children: t("staff.timesheets.my.addRow.noProjects", "No projects assigned") }) : filteredProjects.map((project) => /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              className: "w-full justify-start rounded-none px-3 py-2 text-sm cursor-pointer hover:bg-muted transition-colors",
              onClick: () => handleSelectProject(project),
              children: [
                /* @__PURE__ */ jsx(ProjectColorDot, { colorKey: project.color, projectName: project.name, size: "sm" }),
                /* @__PURE__ */ jsx("span", { className: "ml-1.5", children: project.name })
              ]
            },
            project.id
          )) }),
          canCreateProject && /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              className: "w-full justify-start rounded-none px-3 py-2 text-sm text-primary cursor-pointer hover:bg-muted border-t",
              onClick: handleCreateProject,
              children: [
                /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4 mr-1" }),
                t("staff.timesheets.my.addRow.createProject", "Create a new project")
              ]
            }
          )
        ]
      }
    ),
    document.body
  ) : null;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx("div", { ref: triggerRef, className: "inline-block", children: /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        variant: "ghost",
        className: "flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground cursor-pointer px-3 py-2",
        onClick: handleToggle,
        children: [
          /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" }),
          t("staff.timesheets.my.addRow.trigger", "Add row")
        ]
      }
    ) }),
    dropdown
  ] });
}
export {
  AddRowDropdown
};
//# sourceMappingURL=AddRowDropdown.js.map
