import { Head } from "$fresh/runtime.ts";
import { Handlers, PageProps } from "$fresh/server.ts";
import { RepoData, getRepos, searchRepos } from "../api/repo.ts";
import { useState } from "preact/hooks";
import { SearchBar } from "../components/SearchBar.tsx";
import RepoViewer from "../islands/RepoViewer.tsx";
import Search from "../islands/Search.tsx";
import MySearch from "../islands/MySearchBar.tsx";

export const handler: Handlers = {
  GET: async(req, ctx) => {
    const url = new URL(req.url);
    const searchParams = url.searchParams;
    const query = searchParams.get("q");
    if(query){
      const data = await searchRepos(query);
      return ctx.render({repos:data, query})
    }
    else{
      const data = await getRepos();
      return ctx.render({repos:data, query: ""})
    }
  },
};

export default function Home({ data }: PageProps<{repos: RepoData[], query: string}>) {
  
  return (
    <>
      <Head>
        <title>Search Github Awesome App</title>
      </Head>
      <div class="p-4 mx-auto max-w-screen-md">
        <h1 class="text-4xl font-bold">Search Github Awesome App</h1>
          <MySearch query={data.query}></MySearch>
          <RepoViewer repos={data.repos ?? []} />
      </div>
    </>
  );
}
