"use client";

import Link from "next/link";
import { Button, buttonVariants } from "../ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "../ui/alert-dialog";
import { Input } from "../ui/input";
import {
  banUser,
  sendAlert,
  suspendUser,
  updateBotDiscoverability,
} from "@/lib/actions";
import { useRef, useState } from "react";
import { useToast } from "../ui/use-toast";
import { Bot, User } from "revolt-api";

export function UserActions({ user, bot }: { user: User; bot?: Bot }) {
  const alertMessage = useRef("");
  const { toast } = useToast();

  const [botDraft, setBotDraft] = useState(bot);

  return (
    <div className="flex gap-2">
      {bot ? (
        botDraft!.discoverable ? (
          <Button
            className="flex-1"
            onClick={async () => {
              try {
                await updateBotDiscoverability(bot._id, false);
                setBotDraft((bot) => ({ ...bot!, discoverable: false }));
                toast({
                  title: "Removed bot from Discover",
                });
              } catch (err) {
                toast({
                  title: "Failed to remove bot from Discover",
                  description: "" + err,
                  variant: "destructive",
                });
              }
            }}
          >
            Remove from Discover
          </Button>
        ) : (
          <Button
            className="flex-1"
            onClick={async () => {
              try {
                await updateBotDiscoverability(bot._id, true);
                setBotDraft((bot) => ({ ...bot!, discoverable: true }));
                toast({
                  title: "Added bot to Discover",
                });
              } catch (err) {
                toast({
                  title: "Failed to add bot to Discover",
                  description: "" + err,
                  variant: "destructive",
                });
              }
            }}
          >
            Add to Discover
          </Button>
        )
      ) : (
        <Link
          className={`flex-1 ${buttonVariants()}`}
          href={`/panel/inspect/account/${user._id}`}
        >
          Account
        </Link>
      )}

      <AlertDialog>
        <AlertDialogTrigger asChild>
          <Button className="flex-1 bg-orange-400 hover:bg-orange-300">
            Suspend
          </Button>
        </AlertDialogTrigger>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              Are you sure you want to suspend this user?
            </AlertDialogTitle>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() =>
                suspendUser(user._id)
                  .then(() => toast({ title: "Suspended user" }))
                  .catch((err) =>
                    toast({
                      title: "Failed to suspend user!",
                      description: String(err),
                      variant: "destructive",
                    })
                  )
              }
            >
              Suspend
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <AlertDialog>
        <AlertDialogTrigger asChild>
          <Button className="flex-1" variant="destructive">
            Ban
          </Button>
        </AlertDialogTrigger>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              Are you sure you want to ban this user?
            </AlertDialogTitle>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() =>
                banUser(user._id)
                  .then(() => toast({ title: "Banned user" }))
                  .catch((err) =>
                    toast({
                      title: "Failed to ban user!",
                      description: String(err),
                      variant: "destructive",
                    })
                  )
              }
            >
              Ban
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" className="flex-1">
            More Options
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent>
          <AlertDialog>
            <AlertDialogTrigger className="w-full">
              <DropdownMenuItem
                onClick={() => {
                  throw "Cancel immediate propagation.";
                }}
              >
                Send Alert
              </DropdownMenuItem>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>Send Alert</AlertDialogTitle>
                <AlertDialogDescription className="flex flex-col gap-2">
                  <span>
                    This will send a message from the Platform Moderation
                    account.
                  </span>
                  <Input
                    placeholder="Enter a message..."
                    name="message"
                    onChange={(e) =>
                      (alertMessage.current = e.currentTarget.value)
                    }
                  />
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>Cancel</AlertDialogCancel>
                <AlertDialogAction
                  onClick={() => {
                    if (!alertMessage.current) return;
                    alertMessage.current = "";

                    sendAlert(user._id, alertMessage.current)
                      .then(() => toast({ title: "Sent Alert" }))
                      .catch((err) =>
                        toast({
                          title: "Failed to send alert!",
                          description: String(err),
                          variant: "destructive",
                        })
                      );
                  }}
                >
                  Send
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>

          {/* <DropdownMenuItem>
            Clear ({counts.pending}) Friend Requests
          </DropdownMenuItem>

          <DropdownMenuItem>
            Clear All ({counts.all}) Relations
          </DropdownMenuItem> */}
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}
