"use client";

import { capitalizeFirstLetter } from "@/common/string-utils";
import { useToast } from "@/common/use-toast";
import { getServer, ServerPlatform } from "mcutils-library";
import { useRouter } from "next/navigation";
import { ReactElement, useState } from "react";
import ScaleLoader from "react-spinners/ScaleLoader";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";

type LookupServerProps = {
  /**
   * The last displayed platform.
   */
  currentPlatform: string | undefined;

  /**
   * The last displayed server.
   */
  currentServer: string | undefined;
};

export function LookupServer({ currentPlatform, currentServer }: LookupServerProps): ReactElement {
  const router = useRouter();
  const { toast } = useToast();
  const [loading, setLoading] = useState<boolean>(false);

  /**
   * Lookup a server based on the platform
   *
   * @param platform the server platform
   * @param query the query to lookup
   */
  const lookupServer = async (platform: ServerPlatform, query: string) => {
    if (query == null || query.length === 0) {
      return;
    }

    try {
      setLoading(true);
      const server = await getServer(platform, query);

      // Ignore the same server
      if (currentServer !== undefined && server.hostname == currentServer.toLowerCase()) {
        setLoading(false);
        return;
      }

      router.push(`/server/${platform}/${server.hostname}`);
    } catch (err) {
      toast({
        title: "Error",
        variant: "destructive",
        description: (err as Error).message,
        duration: 5000,
      });
      return setLoading(false);
    }
  };

  return (
    <form
      className="flex flex-col gap-2 justify-center items-center mt-4"
      action={(form: FormData) => {
        lookupServer(form.get("platform") as ServerPlatform, form.get("query") as string);
      }}
    >
      <div className="flex gap-2 justify-center flex-wrap">
        <div className="flex flex-col gap-2 items-start">
          <Label htmlFor="platform">Platform</Label>
          <Select name="platform" defaultValue={currentPlatform}>
            <SelectTrigger className="w-[180px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {Object.entries(ServerPlatform).map(([_, platform], index) => {
                return (
                  <SelectItem key={index} value={platform}>
                    {capitalizeFirstLetter(platform)}
                  </SelectItem>
                );
              })}
            </SelectContent>
          </Select>
        </div>

        <div className="flex flex-col gap-2 items-start">
          <Label htmlFor="query">Hostname</Label>
          <Input className="w-fit" type="search" name="query" placeholder="Query..." maxLength={128} />
        </div>
      </div>

      <Button type="submit" className="flex gap-2">
        {loading && <ScaleLoader width={1} height={20} radius={2} />}
        Search
      </Button>
    </form>
  );
}
