"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { toast } from "@/components/ui/use-toast";
import { lookupEmail, searchUserByTag } from "@/lib/actions";
import { API_URL } from "@/lib/constants";
import { useRouter } from "next/navigation";
import { useState } from "react";

export default function Inspect() {
  const [id, setId] = useState("");
  const [email, setEmail] = useState("");
  const [username, setUsername] = useState("");
  const [discriminator, setDiscriminator] = useState("");
  const router = useRouter();

  const searchEmail = async () => {
    try {
      const result = await lookupEmail(email);
      if (!result) toast({
        title: "Not found",
        description: "There doesn't seem to be any user with this email.",
        variant: "destructive",
      });
      else router.push(`/panel/inspect/account/${result}`);
    } catch(e) {
      toast({
        title: "Failed to look up",
        description: String(e),
        variant: "destructive",
      })
    }
  };

  const searchUsername = async () => {
    try {
      if (!discriminator) {
        // Display all users with this username
        router.push(`/panel/inspect/search?username=${encodeURIComponent(username)}`);
      } else {
        // Show the specific user that matches username#discriminator
        const result = await searchUserByTag(username, discriminator);
        if (!result) toast({
          title: "Couldn't find user",
          variant: "destructive",
        });
        else router.push(`/panel/inspect/user/${result}`);
      }
    } catch(e) {
      toast({
        title: "Failed to search",
        description: String(e),
        variant: "destructive",
      })
    }
  };

  const createHandler = (type: string) => () =>
    router.push(`/panel/inspect/${type}/${id}`);

  return (
    <div className="flex flex-col gap-2">
      <Input
        placeholder="Enter an ID..."
        value={id}
        onChange={(e) => setId(e.currentTarget.value)}
      />
      <div className="flex flex-col md:flex-row gap-2">
        <Button
          className="flex-1"
          variant="outline"
          onClick={createHandler("user")}
        >
          User
        </Button>
        <Button
          className="flex-1"
          variant="outline"
          onClick={createHandler("account")}
        >
          Account
        </Button>
        <Button
          className="flex-1"
          variant="outline"
          onClick={createHandler("server")}
        >
          Server
        </Button>
        <Button
          className="flex-1"
          variant="outline"
          onClick={createHandler("channel")}
        >
          Channel
        </Button>
        <Button
          className="flex-1"
          variant="outline"
          onClick={() =>
            fetch(API_URL + "/invites/" + id)
              .then((res) => res.json())
              .then((invite) =>
                router.push(`/panel/inspect/server/${invite.server_id}`)
              )
          }
        >
          Invite
        </Button>
        <Button
          className="flex-1"
          variant="outline"
          onClick={createHandler("message")}
        >
          Message
        </Button>
      </div>
      <hr />
      <div className="flex flex-col lg:flex-row gap-2 w-full">
        <div className="flex gap-2 justify-between grow">
          <Input
            placeholder="Enter an email..."
            value={email}
            onChange={(e) => setEmail(e.currentTarget.value)}
            onKeyDown={(e) => e.key == "Enter" && email && searchEmail()}
          />
          <Button
            className="flex"
            variant="outline"
            disabled={!email}
            onClick={searchEmail}
          >
            Lookup
          </Button>
        </div>
        <div className="flex gap-2 justify-between grow">
          <div className="flex flex-row items-center w-full gap-1">
            <Input
              placeholder="Username"
              value={username}
              onChange={(e) => setUsername(e.currentTarget.value)}
              onKeyDown={(e) => e.key == "Enter" && username && searchUsername()}
            />
            <span className="select-none text-gray-500">#</span>
            <Input
              placeholder="0000"
              value={discriminator}
              onChange={(e) => setDiscriminator(e.currentTarget.value)}
              onKeyDown={(e) => e.key == "Enter" && username && searchUsername()}
              className="flex-shrink-[2]"
            />
          </div>
          <Button
            className="flex"
            variant="outline"
            disabled={!username}
            onClick={searchUsername}
          >
            Search
          </Button>
        </div>
      </div>
    </div>
  );
}
