/**
 * Copyright (c) 2023-present Pi Dash Software, Inc. and contributors
 * SPDX-License-Identifier: AGPL-3.0-only
 * See the LICENSE file for details.
 */

import { useCallback, useRef, useState } from "react";
import { debounce } from "lodash-es";
import { observer } from "mobx-react";
import { useParams } from "next/navigation";
// pi dash hooks
import { useOutsideClickDetector } from "@pi-dash/hooks";
// helpers
import { useTranslation } from "@pi-dash/i18n";
import { SearchIcon, CloseIcon } from "@pi-dash/propel/icons";
import { cn } from "@pi-dash/utils";
import { useSticky } from "@/hooks/use-stickies";
import { IconButton } from "@pi-dash/propel/icon-button";

export const StickySearch = observer(function StickySearch() {
  // router
  const { workspaceSlug } = useParams();
  // hooks
  const { searchQuery, updateSearchQuery, fetchWorkspaceStickies } = useSticky();
  const { t } = useTranslation();
  // refs
  const inputRef = useRef<HTMLInputElement>(null);
  // states
  const [isSearchOpen, setIsSearchOpen] = useState(false);

  // outside click detector hook
  useOutsideClickDetector(inputRef, () => {
    if (isSearchOpen && searchQuery.trim() === "") setIsSearchOpen(false);
  });
  const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Escape") {
      if (searchQuery && searchQuery.trim() !== "") {
        updateSearchQuery("");
        fetchStickies();
      } else setIsSearchOpen(false);
    }
  };

  const fetchStickies = async () => {
    await fetchWorkspaceStickies(workspaceSlug.toString());
  };

  const debouncedSearch = useCallback(
    debounce(async () => {
      await fetchStickies();
    }, 500),
    [fetchWorkspaceStickies]
  );

  return (
    <div className="my-auto mr-2 flex items-center">
      {!isSearchOpen && (
        <IconButton
          variant="ghost"
          size="lg"
          className="-mr-2"
          icon={SearchIcon}
          onClick={() => {
            setIsSearchOpen(true);
            inputRef.current?.focus();
          }}
        />
      )}
      <div
        className={cn(
          "ml-auto flex w-0 items-center justify-start gap-1 overflow-hidden rounded-md border border-transparent text-placeholder opacity-0 transition-[width] ease-linear",
          {
            "w-30 border-subtle px-2.5 py-1.5 opacity-100 md:w-64": isSearchOpen,
          }
        )}
      >
        <SearchIcon className="size-3.5 shrink-0" />
        <input
          ref={inputRef}
          className="w-full max-w-[234px] border-none bg-transparent text-13 text-primary placeholder:text-placeholder focus:outline-none"
          placeholder={t("Search by title")}
          value={searchQuery}
          onChange={(e) => {
            updateSearchQuery(e.target.value);
            debouncedSearch();
          }}
          onKeyDown={handleInputKeyDown}
        />
        {isSearchOpen && (
          <button
            type="button"
            className="grid place-items-center"
            onClick={() => {
              updateSearchQuery("");
              setIsSearchOpen(false);
              fetchStickies();
            }}
          >
            <CloseIcon className="h-3 w-3" />
          </button>
        )}
      </div>
    </div>
  );
});
