"use client";

import { useToast } from "@/common/use-toast";
import { getPlayer } 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";

type PlayerLookupProps = {
  /**
   * The last displayed player.
   */
  currentPlayer: string;
};

export function LookupPlayer({ currentPlayer }: PlayerLookupProps): 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 lookupPlayer = async (query: string) => {
    if (!query || query.length === 0) {
      return;
    }

    // Ignore the same player
    if (currentPlayer !== undefined && query.toLowerCase() == currentPlayer.toLowerCase()) {
      return;
    }

    try {
      setLoading(true);
      const player = await getPlayer(query);

      router.push(`/player/${player.username}`);
    } catch (err) {
      toast({
        title: "Error",
        variant: "destructive",
        description: (err as Error).message,
        duration: 5000,
      });
      return;
    }
  };

  return (
    <form
      className="flex flex-col gap-2 justify-center items-center mt-4 flex-wrap"
      action={(form: FormData) => {
        lookupPlayer(form.get("query") as string);
      }}
    >
      <div className="flex gap-2 justify-center">
        <div className="flex flex-col gap-2 items-start">
          <Label htmlFor="query">Player</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>
  );
}
