"use client";
import Link from "next/link";
import styles from "./styles.module.css";
import { FormEvent, KeyboardEvent, useRef, useState } from "react";
import { stringify } from "querystring";
import { ConditionalNull } from "@/components/utility/Conditional";
import { useRouter } from "next/navigation";

export default function Searchbar({value}:{value?:string}) {
  const [href, setHref] = useState<string>("");
  const [arr, setArr] = useState<string[]>([]);
  const searchRouter = useRouter();

  let currentTimeout: number | NodeJS.Timeout;
  function suggestTimeout(e:FormEvent<HTMLInputElement>) {
    const target = e.target as HTMLInputElement;
    if (target.value.length < 1)
      setHref("");
    else
      setHref(`/search/search/?${stringify({q:target.value})}`);
    clearTimeout(currentTimeout);
    currentTimeout = setTimeout(executeAC, 500, e);
  }

  async function executeAC(e:FormEvent<HTMLInputElement>) {
    const target = e.target as HTMLInputElement;
    console.log(target.value);
    const rows = await fetch(`/search/autocompleter?${stringify({
      q: target.value
    })}`).then(x => x.json());
    if (rows == null) return;
    setArr(rows[1]);
  }

  function onKeypress(e:KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter") {
      // Cancel the default action, if needed
      e.preventDefault();
      searchRouter.push(href);
      
    }
  }

  return (<>
      <div className={styles.SearchBox}>
        <input 
          type="text" name="q" className={styles.SearchBoxForm}
          autoCorrect="off"
          autoComplete="off"
          onInput={suggestTimeout}
          onKeyDown={onKeypress}
          placeholder="Search s.abtmtr.link"
          defaultValue={value}
        ></input>
        <Link className={styles.SearchBoxButton} href={href}>search</Link>
      </div>
      <ConditionalNull condition={arr.length > 0}>
        <div className={styles.SuggestionBox}>
          {arr.map(result => (
            <div className={styles.SuggestionBoxIndex}>
              <Link href={`/search/search/?${stringify({q:result})}`}>
                {result}
              </Link>
            </div>
          ))}
        </div>
      </ConditionalNull></>
  )
}