import { Box, Button } from "@mui/material"
import { margin } from "@mui/system";
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { setCredentialsInitial, setNull } from "../../store/authSlice";
import { useGetUserByIdQuery } from "../../store/categoriesApi";
import OrdersTableCollaps from "../OrdersTableCollaps";
import ProfileMutationForm from "../ProfileMutationForm";


const ProfilePage = () => {
  const dispatch = useDispatch()
  const userAuth = useSelector((state) => state.auth.user)
  const navigate = useNavigate()
  const [EditProfileIsOpen, setEditProfileIsOpen] = useState(false)

  const _id = userAuth ? userAuth.sub.id : null
  const userRole = userAuth ? userAuth.sub.acl[2] || userAuth.sub.acl[1] : null
  console.log(userRole)
  const { data: payload = null } = useGetUserByIdQuery(_id)
  const user = payload ? Object.values(payload)[0] : null


  return (
    <Box width={'100%'} >
      <Box width={'100%'} mb={2} p={1} sx={{ display: 'flex', justifyContent: "space-between" }}>
        <h2>привет: {user?.nick}!</h2>
        <Box sx={{ '& > *': { margin: '2px' } }}>
          {userRole === "admin" && <Button variant="outlined" onClick={() => navigate('/admin')}>панель администратора</Button>}
          <Button variant="outlined" onClick={() => {setEditProfileIsOpen(!EditProfileIsOpen) }}>редактировать профиль</Button>
          <Button variant="outlined" onClick={() => { dispatch(setCredentialsInitial()); navigate('/') }}>выйти</Button>
        </Box>
      </Box>
      <Box sx={{margin: '50px 10px'}}>
        {user && EditProfileIsOpen && <ProfileMutationForm user = {user}/>}
      </Box>
      <Box >
        <OrdersTableCollaps />
      </Box>
    </Box>
  )
}

export default ProfilePage