import { MagnifyingGlassIcon, XIcon } from '@phosphor-icons/react'
import { useRef } from 'react'

import { IconButton } from '../IconButton'

interface SearchInputProps {
  searchQuery: string
  setSearchQuery: (value: string) => void
  placeholder: string
}

export function SearchInput({
  searchQuery,
  setSearchQuery,
  placeholder,
}: SearchInputProps) {
  const searchInputRef = useRef<HTMLInputElement>(null)

  return (
    <div className="relative">
      <MagnifyingGlassIcon
        className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-stone"
        weight="bold"
      />

      <input
        ref={searchInputRef}
        type="text"
        placeholder={placeholder}
        value={searchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
        className="w-full pl-10 pr-10 py-3 text-sm border border-sand rounded-xl focus:outline-none focus:ring-2 focus:ring-black focus:border-transparent"
      />

      {searchQuery && (
        <IconButton
          label="Clear search"
          onClick={() => {
            setSearchQuery('')
            searchInputRef.current?.focus()
          }}
          className="absolute right-3 top-1/2 -translate-y-1/2 p-1 text-stone hover:text-charcoal"
        >
          <XIcon className="h-4 w-4" weight="bold" />
        </IconButton>
      )}
    </div>
  )
}
