"use client";

import { useToast } from "@/common/use-toast";
import { getPlayer } 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 LookupPlayer(): JSX.Element {
  const router = useRouter();
  const { toast } = useToast();
  const [id, setId] = useState("");

  /**
   * Lookup a player
   */
  const lookupPlayer = async () => {
    if (!id || id.length === 0) {
      return;
    }

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

    router.push(`/player/${id}`);
  };

  return (
    <form className="flex gap-2 justify-center mt-2" action="" onSubmit={(event) => event.preventDefault()}>
      <Input
        className="w-fit"
        type="search"
        name="query"
        placeholder="Name / UUID"
        value={id}
        onChange={(event) => {
          setId(event.target.value);
        }}
        maxLength={36}
      />
      <Tooltip>
        <TooltipTrigger asChild>
          <Button type="submit" onClick={() => lookupPlayer()}>
            Lookup
          </Button>
        </TooltipTrigger>
        <TooltipContent>
          <p>Click to lookup the player</p>
        </TooltipContent>
      </Tooltip>
    </form>
  );
}
