'use client';

import { useRouter, useSearchParams } from 'next/navigation';

const SearchInput: React.FC = () => {
  const router = useRouter();
  const params = useSearchParams();

  function updateQuery(value: string) {
    const updatedParams = new URLSearchParams(params.toString());
    if (value) {
      updatedParams.set('query', value);
    } else {
      updatedParams.delete('query');
    }

    router.replace(`?${updatedParams.toString()}`);
  }

  return (
    <label>
      Filter:
      <input
        type="text"
        defaultValue={params.get('query') || ''}
        placeholder="Suche nach Büchern..."
        onChange={(changeEvent) => updateQuery(changeEvent.target.value)}
      />
    </label>
  );
};

export default SearchInput;
