import { useEffect, useReducer } from "react";
import { getServerList, type Server } from "../../Lib/Servers";
import ServerSearch from "../../Components/ServerSearch/ServerSearch";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Spinner } from "react-bootstrap";
import Cookies from "js-cookie";

type serverListAction = { type: "CLEAR" } | { type: "SET", payload: Server[] };

const serverReducer = (state: Server[], action: serverListAction): Server[] => {
  switch (action.type) {
    case "CLEAR":
      return [];
    case "SET":
      return action.payload;
    default:
      return state;
  }
}

const Search = () => {
  const [searchParams] = useSearchParams();
  // const [servers, setServers] = useState<Array<Server>>([]);
  const [servers, serversDispatch] = useReducer(serverReducer, []);
  const navigate = useNavigate();
  const sessionCookie = Cookies.get("session");

  const searchTerm = searchParams.get("search") || "";

  useEffect(() => {
    serversDispatch({ type: "CLEAR" });

    if (!sessionCookie) {
      navigate("/login");
      return;
    }

    if (searchTerm === "") {
      alert(`Error search term missing: ${searchTerm}`);
      navigate("/");
    }

    getServerList().then(servers => {
      if (servers.length === 0) {
        alert("No servers found");
      }

      const workingServers: Array<Server> = [];

      servers.forEach(s => {
        if (!s.errored) {
          workingServers.push(s);
        }
      })

      if (workingServers.length === 0) {
        alert("No working servers");
        navigate("/");
      }

      serversDispatch({ type: "SET", payload: workingServers });
    }).catch(e => {
      alert(e);
    });
  }, [searchTerm, navigate, sessionCookie]);

  return (
    <>
      {servers.length > 0 ? servers.map(server => {
        return <ServerSearch searchTerm={searchTerm} server={server} />
      })
        :
        <Spinner />}
    </>
  )
}

export default Search;