"use client";

import React from "react";
import { Button } from "@/components/ui/button";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { api } from "@/trpc/react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";

function LobbyMembershipDialog({
  lobbyId,
  join,
}: {
  lobbyId: string;
  join: boolean;
}) {
  const [loading, setLoading] = React.useState(false);
  const { mutateAsync } = api.lobby.membership.useMutation();
  const router = useRouter();
  const handleConfirm = async () => {
    setLoading(true);
    const result = await mutateAsync({ lobbyId, join });
    if (result) {
      if (!join) router.push("/");
      else toast.success("Successfully joined the lobby.");
    } else toast.error("Something went wrong");
    setLoading(false);
  };

  const labelText = join ? "join" : "leave";

  return (
    <AlertDialog>
      <Button asChild>
        <AlertDialogTrigger className="capitalize">
          {labelText} Lobby
        </AlertDialogTrigger>
      </Button>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle className="capitalize">
            {labelText} Lobby
          </AlertDialogTitle>
          <AlertDialogDescription>
            You are about to {labelText} the lobby.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction
            onClick={handleConfirm}
            disabled={loading}
            className="capitalize"
          >
            {labelText}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}

export default LobbyMembershipDialog;
