"use client";

import React from "react";
import {
  Menu,
  MenuItem,
  IconButton,
  ListItemIcon,
  Typography,
  Button,
  CircularProgress,
} from "@mui/material";
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import SettingsIcon from "@mui/icons-material/Settings";
import LogoutIcon from "@mui/icons-material/Logout";
import { useDispatch, useSelector } from "react-redux";
import { selectIsLoggedIn, selectStatus } from "@/app/redux/auth/selectors";
import { logout } from "@/app/redux/auth/authSlice";
import { AppDispatch } from "@/app/redux/types";
import { useRouter } from "next/navigation";

export default function AccountMenu() {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const dispatch = useDispatch<AppDispatch>();
  const router = useRouter();

  // Select relevant state from your auth slice
  const isLoggedIn = useSelector(selectIsLoggedIn);
  const authStatus = useSelector(selectStatus);

  // Determine if we're currently in the process of logging out
  const isLoggingOut = authStatus === "loading";

  const handleLogout = async () => {
    // Dispatch the logout thunk
    const resultAction = await dispatch(logout());

    // Check if logout was successful based on the action result
    if (logout.fulfilled.match(resultAction)) {
      console.log("Logout successful, redirecting...");
      router.push("/login"); // Redirect to your login page
    } else {
      // Handle logout failure (e.g., show an error message)
      console.error("Logout failed:", resultAction.payload);
      // You might want to display a toast or alert here
    }
  };

  // Only show the logout button if the user is logged in
  // if (!isLoggedIn) {
  //   return null;
  // }

  return (
    <>
      <IconButton onClick={handleClick} color="inherit">
        <AccountCircleIcon />
      </IconButton>

      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        onClick={handleClose}
        transformOrigin={{ horizontal: "right", vertical: "top" }}
        anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
      >
        <MenuItem>
          <ListItemIcon>
            <AccountCircleIcon fontSize="small" />
          </ListItemIcon>
          <Typography variant="inherit">Account</Typography>
        </MenuItem>

        <MenuItem>
          <ListItemIcon>
            <SettingsIcon fontSize="small" />
          </ListItemIcon>
          <Typography variant="inherit">Settings</Typography>
        </MenuItem>

        <MenuItem>
          <ListItemIcon>
            <LogoutIcon fontSize="small" />
          </ListItemIcon>
          <Button
            variant="contained"
            color="secondary"
            onClick={handleLogout}
            disabled={isLoggingOut}
            startIcon={
              isLoggingOut ? (
                <CircularProgress size={20} color="inherit" />
              ) : null
            }
          >
            {isLoggingOut ? "Logging Out..." : "Logout"}
          </Button>
        </MenuItem>
      </Menu>
    </>
  );
}
