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

import { cn } from '../lib/utils'
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupInput
} from './ui/input-group'

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(
    ['forwardslash'],
    () => {
      inputRef.current?.focus()
    },
    {
      exactMatch: true,
      events: ['keyup'],
      useCapture: true,
      target: () => window
    }
  )

  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>
  )
}
