"use client";

import * as React from "react";

import { Search } from "lucide-react";

import { Button } from "@/components/ui/button";
import type { CustomerNavigationPayload } from "@/navigation/sidebar/dynamic-sidebar";

const SearchDialogContent = React.lazy(() =>
  import("./search-dialog-content").then((module) => ({ default: module.SearchDialogContent })),
);

type SearchDialogProps = {
  tenant?: string | null;
  navigation?: CustomerNavigationPayload | null;
  allowedRoutes?: readonly string[];
};

export function SearchDialog({ tenant = null, navigation = null, allowedRoutes }: SearchDialogProps) {
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    const down = (e: KeyboardEvent) => {
      if (e.key?.toLowerCase() === "j" && (e.metaKey || e.ctrlKey) && !e.shiftKey) {
        e.preventDefault();
        setOpen((prev) => !prev);
      }
    };
    document.addEventListener("keydown", down);
    return () => document.removeEventListener("keydown", down);
  }, []);

  return (
    <>
      <Button
        onClick={() => setOpen(true)}
        variant="link"
        className="px-0! font-normal text-muted-foreground hover:no-underline"
      >
        <Search data-icon="inline-start" />
        Search
        <kbd className="inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-medium text-[10px]">
          <span className="text-xs">⌘</span>J
        </kbd>
      </Button>
      {open ? (
        <React.Suspense fallback={null}>
          <SearchDialogContent
            open={open}
            onOpenChange={setOpen}
            tenant={tenant}
            navigation={navigation}
            allowedRoutes={allowedRoutes}
          />
        </React.Suspense>
      ) : null}
    </>
  );
}
