import { RepoData, getRepos, searchRepos } from "../api/repo.ts";
import { useEffect, useRef, useState } from "preact/hooks";
import { SearchBar } from "../components/SearchBar.tsx";
import { useRelativeTopOppacity } from "../util/hook.ts";

function RepoTag(props: { tag: string }) {
    const { tag } = props;
    return (
      <a href={`https://github.com/topics/${tag}`}
      class="inline-flex items-center px-2 py-1 m-1 text-xs font-medium leading-5 text-blue-800 bg-blue-100 rounded-full">
        {tag}
      </a>
    );
  }
  
function RepoItem(props: RepoData) {
    const ref = useRef<HTMLDivElement | null>(null);
    const opacity = useRelativeTopOppacity({elem: ref});
    const { name, description, url, author, stars, tags, forks } = props;
    return (
      <div ref={ref} class="flex flex-col bg-white rounded transition-opacity"
        style={`opacity: ${opacity}`}>
        <div class="flex flex-col flex-grow p-4">
          <a class="text-xl font-bold text-gray-900 hover:text-gray-700 flex-auto"
              href={url}>{author+"/"+name}</a>
          <div class="flex flex-row">
              <p class="text-gray-600 ml-2 text-xs">
                {forks} forks
              </p>
              <p class="text-gray-600 ml-2 text-xs">
                {stars} stars
              </p>
          </div>
          <p class="mt-2 text-gray-600">{description}</p>
          <div class="flex flex-wrap mt-4 -m-1">
            {tags.map(tag => (
              <RepoTag tag={tag} />
            ))}
          </div>
        </div>
      </div>
    );
  }
  
export default function RepoViewer({repos}: {repos: RepoData[]}) {
    return (
        <div class="mt-4">
            {repos.length > 0 ? (
                <ul class="divide-y divide-gray-200">
                    {repos.map((repo) => (
                        <li class="py-4">
                            <RepoItem {...repo} />
                        </li>
                    ))}
                </ul>
            ) : (
                <p class="text-gray-500">No results found.</p>
            )}
        </div>
    );
}
