"use client";

import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useState } from "react";
import { signOut } from "next-auth/react";
import { useLogout } from "@/state/auth/auth.action";
import { useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import IconButton from "../icon-button/icon-button";

interface LogoutConfirmationDialogProps {
  isOpen: boolean;
  onOpenChange: (isOpen: boolean) => void;
}

export function LogoutConfirmationDialog({
  isOpen,
  onOpenChange,
}: LogoutConfirmationDialogProps) {
  const [isLoggingOut, setIsLoggingOut] = useState(false);
  const { mutate: logOut } = useLogout();
  const router = useRouter();
  const queryClient = useQueryClient();

  const handleLogout = async () => {
    setIsLoggingOut(true);

    logOut(
      { id: "", payload: {} },
      {
        onSuccess: async () => {
          await signOut({ redirect: false });

          // clear local/session state
          window.localStorage.clear();
          queryClient.clear();
          onOpenChange(false);

          // reload to ensure fresh state
          window.location.href = "/";
          // OR
          // window.location.reload(); // stays on same path, but reloads everything
        },
        onError: (err) => {
          console.error("❌ Logout failed:", err);
          setIsLoggingOut(false);
        },
      }
    );
  };

  return (
    <AlertDialog open={isOpen} onOpenChange={onOpenChange}>
      <AlertDialogContent className="bg-[#181818] text-white p-4 rounded-2xl sm:max-w-md border-gray-700 shadow-2xl">
        <AlertDialogHeader>
          <AlertDialogTitle className="text-white">
            Are you sure you want to log out?
          </AlertDialogTitle>
          <AlertDialogDescription className="text-gray-400">
            You will be returned to the homepage and will need to sign in again
            to access your account.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <IconButton
            label={"Cancel"}
            iconShow={false}
            onClick={() => onOpenChange(false)}
            disabled={isLoggingOut}
          />
          <IconButton
            label={isLoggingOut ? "Logging out..." : "Logout"}
            iconShow={false}
            onClick={handleLogout}
            disabled={isLoggingOut}
          />
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
