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

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

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

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

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

  const debouncedOnChange = debounce((value: string) => {
    onChange?.(value)
  }, 200)

  return (
    <InputGroup className="group">
      <InputGroupInput
        className={cn('peer', className)}
        placeholder=" "
        ref={inputRef}
        defaultValue={defaultValue}
        onChange={(e) => debouncedOnChange(e.target.value)}
        {...props}
      />

      <InputGroupAddon>
        <SearchIcon />
      </InputGroupAddon>

      {placeholder && (
        <InputGroupAddon className="font-normal hidden peer-focus-within:hidden peer-placeholder-shown:block">
          {placeholder}
        </InputGroupAddon>
      )}

      {defaultValue && (
        <InputGroupAddon align="inline-end">
          <InputGroupButton
            size="icon-xs"
            className="cursor-pointer"
            onClick={() => {
              if (inputRef.current) {
                inputRef.current.value = ''
              }
              onChange?.('')
              inputRef.current?.focus()
            }}
          >
            <XIcon />
          </InputGroupButton>
        </InputGroupAddon>
      )}
    </InputGroup>
  )
}
