import { useNavigate } from "react-router-dom";
import {
  Box,
  IconButton,
  Typography,
  useTheme,
  useMediaQuery,
} from "@mui/material";
import LogoutIcon from "../icons/LogoutIcon";
import CustomAvatar from "./Avatar";
import Drawers from "../Drawers";
import { logout } from "@root/api/auth";
import { enqueueSnackbar } from "notistack";
import { clearUserData, useUserStore } from "@root/stores/user";
import { clearAuthToken, getMessageFromFetchError } from "@frontend/kitui";
import { clearCustomTariffs } from "@root/stores/customTariffs";
import { clearTickets } from "@root/stores/tickets";

import { currencyFormatter } from "@root/utils/currencyFormatter";

import walletIcon from "@root/assets/Icons/wallet_icon.svg";

export const NavbarPanel = () => {
  const navigate = useNavigate();
  const theme = useTheme();
  const isTablet = useMediaQuery(theme.breakpoints.down(1000));
  const cash = useUserStore((state) => state.userAccount?.wallet.cash) ?? 0;

  async function handleLogoutClick() {
    try {
      await logout();
      clearAuthToken();
      clearUserData();
      clearCustomTariffs();
      clearTickets();
      navigate("/");
    } catch (error: any) {
      const message = getMessageFromFetchError(error, "Не удалось выйти");
      if (message) enqueueSnackbar(message);
    }
  }

  return (
    <Box sx={{ display: "flex", ml: "auto" }}>
      <Drawers />
      <IconButton
        sx={{
          display: "flex",
          alignItems: "center",
          ml: isTablet ? "10px" : "20px",
          bgcolor: "#F2F3F7",
          borderRadius: "6px",
          height: "36px",
          width: "36px",
        }}
        onClick={() => navigate("/wallet")}
      >
        <img src={walletIcon} alt="wallet" />
      </IconButton>
      <Box sx={{ ml: "8px", whiteSpace: "nowrap" }}>
        <Typography
          sx={{
            fontSize: "12px",
            lineHeight: "14px",
            color: theme.palette.gray.dark,
          }}
        >
          Мой баланс
        </Typography>
        <Typography variant="body2" color={theme.palette.purple.main}>
          {currencyFormatter.format(cash / 100)}
        </Typography>
      </Box>
      <CustomAvatar />
      <IconButton
        onClick={handleLogoutClick}
        sx={{
          ml: "20px",
          bgcolor: "#F2F3F7",
          borderRadius: "6px",
          height: "36px",
          width: "36px",
        }}
      >
        <LogoutIcon />
      </IconButton>
    </Box>
  );
};
