"use client";

import { capitalizeFirstLetter } from "@/common/string-utils";
import { ServerPlatform } from "mcutils-library";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";

export function LookupServer(): JSX.Element {
  const router = useRouter();
  const [hostname, setHostname] = useState("");

  /**
   * Set the hostname value
   *
   * @param event the input event
   */
  const setHostnameValue = (event: React.ChangeEvent<HTMLInputElement>) => {
    setHostname(event.target.value);
  };

  /**
   * Lookup a server based on the platform
   *
   * @param platform the server platform
   */
  const lookupServer = (platform: ServerPlatform) => {
    if (!hostname || hostname.length === 0) {
      return;
    }
    router.push(`/server/${platform}/${hostname}`);
  };

  const LookupButton = ({ platform }: { platform: ServerPlatform }): JSX.Element => {
    const name = capitalizeFirstLetter(platform);
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <Button type="submit">{name}</Button>
        </TooltipTrigger>
        <TooltipContent>
          <p>Click to lookup the server as a {name} server</p>
        </TooltipContent>
      </Tooltip>
    );
  };

  return (
    <form className="flex gap-2 justify-center items-center mt-2 flex-col xs:flex-row">
      <Input className="w-fit" placeholder="Hostname" value={hostname} onChange={setHostnameValue} maxLength={128} />
      <div className="flex gap-2 justify-center">
        <LookupButton platform={ServerPlatform.Java} />
        <LookupButton platform={ServerPlatform.Bedrock} />
      </div>
    </form>
  );
}
