'use client'
import { type ButtonProps, buttonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { useSearchContext } from 'fumadocs-ui/contexts/search'
import { SearchIcon } from 'lucide-react'
import type { ButtonHTMLAttributes } from 'react'

export function SearchToggle({
  hideIfDisabled,
  size = 'icon',
  variant = 'ghost',
  ...props
}: ButtonHTMLAttributes<HTMLButtonElement> &
  ButtonProps & {
    hideIfDisabled?: boolean
  }) {
  const { setOpenSearch, enabled } = useSearchContext()
  if (hideIfDisabled && !enabled) return null

  return (
    <button
      type='button'
      className={cn(
        buttonVariants({
          size,
          variant,
        }),
        props.className
      )}
      data-search=''
      aria-label='Open Search'
      onClick={() => {
        setOpenSearch(true)
      }}
    >
      <SearchIcon />
    </button>
  )
}

export function LargeSearchToggle({
  hideIfDisabled,
  ...props
}: ButtonHTMLAttributes<HTMLButtonElement> & {
  hideIfDisabled?: boolean
}) {
  const { enabled, hotKey, setOpenSearch } = useSearchContext()
  if (hideIfDisabled && !enabled) return null

  return (
    <button
      type='button'
      data-search-full=''
      {...props}
      className={cn(
        'inline-flex items-center gap-2 rounded-full border bg-fd-secondary/50 p-1.5 text-fd-muted-foreground text-sm transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground',
        props.className
      )}
      onClick={() => {
        setOpenSearch(true)
      }}
    >
      <SearchIcon className='ms-1 size-4' />
      Search
      <div className='ms-auto inline-flex gap-0.5'>
        {hotKey.map((k, i) => (
          <kbd key={i} className='rounded-md border bg-fd-background px-1.5'>
            {k.display}
          </kbd>
        ))}
      </div>
    </button>
  )
}
