"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { toast } from "@/components/ui/use-toast";
import { lookupEmail } 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 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 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 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 gap-2 justify-between">
        <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>
  );
}
