import { useRouter } from "next/router";
import { ChangeEvent, FormEvent, useEffect, useMemo, useState } from "react";

export default function SearchForm() {
  const { asPath, query, push } = useRouter();
  const inSearchPage = useMemo(() => {
    return !/\/novels/.test(asPath);
  }, [asPath]);

  const [value, setValue] = useState("");

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    push(`${asPath.split("?")[0]}${value ? `?q=${value}` : ""}`);
  };

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  };

  useEffect(() => {
    setValue((query.q as string) || "");
  }, [query.q]);

  return (
    <form
      action={inSearchPage ? asPath : "/novels"}
      className="search-input"
      onSubmit={handleSubmit}
    >
      <svg className="icon-search">
        <use xlinkHref="/icons.svg#search"></use>
      </svg>
      <input
        type="search"
        name="q"
        placeholder="Search"
        value={value}
        onChange={handleChange}
      />
    </form>
  );
}
