'use client';

import {useEffect, useMemo, useState} from 'react';
import {useRouter} from 'next/navigation';
import {CommandPalette} from '@astryxdesign/core/CommandPalette';
import {createStaticSource} from '@astryxdesign/core/Typeahead';
import {Button} from '@astryxdesign/core/Button';
import {IconButton} from '@astryxdesign/core/IconButton';
import {Icon} from '@astryxdesign/core/Icon';
import {useBreakpoint} from '@/lib/breakpoints';
import {FOOTER_NAV, PRIMARY_NAV} from './nav-config';

/**
 * Search is a command palette, not a text field. In a workspace this dense the
 * fastest path to anything is ⌘K → type → Enter, so the thing in the nav bar
 * is an affordance that opens the palette rather than an input of its own.
 *
 * Right now it indexes navigation only. Stores, rewards and staff join the
 * same source once their modules land — the palette does not change, only the
 * items array does.
 */
export function GlobalSearch() {
  const [isOpen, setIsOpen] = useState(false);
  const router = useRouter();
  const isCompact = useBreakpoint() === 'mobile';

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key.toLowerCase() === 'k' && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        setIsOpen((v) => !v);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const source = useMemo(
    () =>
      createStaticSource(
        [...PRIMARY_NAV, ...FOOTER_NAV].map((n) => ({
          id: n.href,
          label: n.label,
          auxiliaryData: {group: 'Navigate', href: n.href},
        })),
      ),
    [],
  );

  return (
    <>
      {/*
        Icon-only on phones. The ⌘K affordance is the point of the wide form,
        and a phone has no ⌘ — spending 110px of a 375px bar advertising a
        shortcut that cannot be pressed would push the profile menu off it.
      */}
      {isCompact ? (
        <IconButton
          variant="ghost"
          size="lg"
          label="Search"
          tooltip="Search"
          icon={<Icon icon="search" />}
          onClick={() => setIsOpen(true)}
          className="size-11"
        />
      ) : (
        <Button
          variant="secondary"
          size="sm"
          label="Search  ⌘K"
          icon={<Icon icon="search" size="sm" />}
          onClick={() => setIsOpen(true)}
        />
      )}
      <CommandPalette
        isOpen={isOpen}
        onOpenChange={setIsOpen}
        searchSource={source}
        label="Search Loyaly"
        emptyBootstrapText="Search stores, rewards and staff…"
        onValueChange={(value) => {
          router.push(value);
          setIsOpen(false);
        }}
      />
    </>
  );
}
