"use client";

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

export function LookupServer(): ReactElement {
  const router = useRouter();
  const { toast } = useToast();
  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 = async (platform: ServerPlatform) => {
    if (!hostname || hostname.length === 0) {
      return;
    }

    try {
      await getServer(platform, hostname);
    } catch (err) {
      toast({
        title: "Error",
        variant: "destructive",
        description: (err as Error).message,
        duration: 5000,
      });
      return;
    }

    router.push(`/server/${platform}/${hostname}`);
  };

  const LookupButton = ({ platform }: { platform: ServerPlatform }): ReactElement => {
    const name = capitalizeFirstLetter(platform);
    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <Button type="submit" onClick={() => lookupServer(platform)}>
            {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"
      action=""
      onSubmit={event => event.preventDefault()}
    >
      <Input
        className="w-fit"
        type="search"
        name="query"
        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>
  );
}
