import { debounce } from 'lodash'
import { SearchIcon } from 'lucide-react'
import { useRef } from 'react'

import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput
} from '@/components/ui/input-group'

import { useKeyPress } from '@/hooks/use-keypress'
import { cn } from '@/lib/utils'

export function SearchForm({
  placeholder,
  className,
  onChange,
  ...props
}: {
  placeholder?: React.ReactNode
  className?: string
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void
} & React.HTMLAttributes<HTMLDivElement>) {
  const inputRef = useRef<HTMLInputElement>(null)

  useKeyPress('/', () => {
    inputRef.current?.focus()
  })

  return (
    <InputGroup className="group">
      <InputGroupInput
        className={cn('peer', className)}
        placeholder=" "
        ref={inputRef}
        onChange={debounce(onChange, 200)}
        {...props}
      />
      <InputGroupAddon>
        <SearchIcon />
      </InputGroupAddon>
      <InputGroupAddon className="font-normal hidden peer-focus-within:hidden peer-placeholder-shown:block">
        {placeholder}
      </InputGroupAddon>
    </InputGroup>
  )
}
