"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";
import { appRoutes } from "@/config/app.routes";

function LobbyMembershipDialog({
  lobbyId,
  join,
}: {
  lobbyId: string;
  join: boolean;
}) {
  const [loading, setLoading] = React.useState(false);
  const labelText = join ? "join" : "leave";
  const router = useRouter();
  const membership = api.lobby.membership.useMutation({
    onSuccess(data) {
      if (data?.success) {
        toast.success(`Successfully ${labelText} the lobby.`);
        if (join) router.push(appRoutes.currentlobby);
        else router.push(appRoutes.lobby(lobbyId));
        router.refresh();
      } else {
        if (data?.knownError) {
          toast.message(data.error, {
            action: {
              label: "Jump to Lobby",
              onClick: () => router.push(appRoutes.currentlobby),
            },
          });
        }
      }
    },
  });
  const handleConfirm = async () => {
    setLoading(true);
    try {
      await membership.mutateAsync({
        lobbyId,
        join,
      });
    } catch (e) {
      // Catching any errors here will prevent them from reaching Next.js's error boundary
      console.error("Handled mutation error:", e);
    }

    setLoading(false);
  };

  return (
    <AlertDialog>
      <Button asChild variant={join ? "default" : "destructive"}>
        <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} Lobby
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}

export default LobbyMembershipDialog;
