import { Doc } from "../src/collect.ts";
import { useEffect, useState } from "preact/hooks";
import { Index } from "../src/client_search.ts";
import { encodePath } from "../util/util.ts";
import { join } from "path/mod.ts";

function SearchBar(props: {
  search?: string;
  onSearch?: (search: string) => void;
}) {
  const [search, setSearch] = useState(props.search ?? "");
  return (
    <div class="flex items-center justify-center">
      <input
        type="text"
        class="w-1/2 px-4 py-2 border-2 rounded-lg"
        placeholder="Search..."
        //onChange={(event)=>{}}
        onKeyUp={(event) => {
          if (event.currentTarget.value === search) return;
          setSearch(event.currentTarget.value);
          props.onSearch?.(event.currentTarget.value);
        }}
      >
        {search}
      </input>
    </div>
  );
}

export default function DocSearch(props: {
  docs: Doc[];
}) {
  const [docs, setDocs] = useState(props.docs);
  const index = Index.createIndex(props.docs);

  return (
    <>
      <SearchBar
        onSearch={(s) => {
          setDocs(index.search(s));
        }}
      />
      <h1 class="text-2xl font-bold">Doc</h1>
      <ul class="mt-4">
        {docs.map((doc) => {
          const path = join(doc.path, "..");
          return (
            <li class="mt-2" key={path}>
              <a href={`/dir/${encodePath(path)}?pretty`}>{path}</a>
            </li>
          );
        })}
      </ul>
    </>
  );
}
