import { useEffect, useState } from "react";
import { Spinner, Table } from "react-bootstrap";
import ServerSearchResult from "./ServerSearchResult/ServerSearchResult";
import type { Server } from "../../Lib/Servers";
import { search, type SearchResult } from "../../Lib/Search";

interface ServerSearchProps {
  searchTerm: string;
  server: Server;
}

const ServerSearch = ({ searchTerm, server }: ServerSearchProps) => {
  const [searchResults, setSearchResults] = useState<Array<SearchResult | undefined>>();

  useEffect(() => {
    search(searchTerm, server.url).then(results => {
      setSearchResults(results);
    }).catch(err => {
      setSearchResults([]);
      alert(err);
    })
  }, [searchTerm]);

  return (
    <Table striped bordered >
      <thead>
        <tr>
          <th>{server.owner}'s server</th>
        </tr>
      </thead>
      <tbody>
        {searchResults ?
          searchResults.length > 0 ?
            searchResults.map(result => {
              return (
                <tr key={result!.id}>
                  <td>
                    <ServerSearchResult searchResult={result!} server={server} />
                  </td>
                </tr>
              )
            })
            :
            <tr>
              <td>
                <h1>No results found</h1>
              </td>
            </tr>
          :
          <Spinner />
        }
      </tbody>
    </Table >

    // <div>
    //   <div>
    //     <h1>{server.name}</h1>
    //   </div>
    //   <div>
    //     {searchResults.length > 0 ?
    //       searchResults.map(result => {
    //         return <ServerSearchResult key={result.id} searchResult={result} server={server} />
    //       })
    //       :
    //       <Spinner />
    //     }
    //   </div>
    // </div>
  )
}

export default ServerSearch;