import * as React from 'react';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import ListItemIcon from '@mui/material/ListItemIcon';
import MenuItem from '@mui/material/MenuItem';
import MenuList from '@mui/material/MenuList';
import Popover from '@mui/material/Popover';
import Typography from '@mui/material/Typography';
import {SignOut as SignOutIcon} from '@phosphor-icons/react/dist/ssr/SignOut';
import {SignIn as SignInIcon} from '@phosphor-icons/react/dist/ssr/SignIn';
import {logger} from "../../lib/DefaultLogger";
import {useAuth} from "../../hooks/useAuth";
import {authClient} from "../../lib/clients/AuthClient";
import {useLocation} from "react-router-dom";
import {useUser} from "../../hooks/useUser";
import {paths} from "../../path";

export function UserPopover({anchorEl, onClose, open}) {
    const {checkSession} = useAuth();
    const {user, session} = useUser();

    const location = useLocation();

    const handleSignOut = React.useCallback(async () => {
        try {
            const {error} = await authClient.signOut();

            if (error) {
                logger.error('Sign out error', error);
                return;
            }

            // Refresh the auth state
            await checkSession?.();

            // UserProvider, for this case, will not refresh the router and we need to do it manually
            window.location.reload();
            // After refresh, AuthGuard will handle the redirect
        } catch (err) {
            logger.error('Sign out error', err);
        }
        // eslint-disable-next-line
    }, [checkSession, location]);

    return (
        <Popover
            anchorEl={anchorEl}
            anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
            onClose={onClose}
            open={open}
            slotProps={{paper: {sx: {width: '240px'}}}}
        >
            <Box sx={{p: '16px 20px '}}>
                {userDescriptor(user, session)}
            </Box>
            <Divider/>
            <MenuList disablePadding sx={{p: '8px', '& .MuiMenuItem-root': {borderRadius: 1}}}>
                {/*<MenuItem component={'a'} href={paths.dashboard.settings} onClick={onClose}>*/}
                {/*    <ListItemIcon>*/}
                {/*        <GearSixIcon fontSize="var(--icon-fontSize-md)"/>*/}
                {/*    </ListItemIcon>*/}
                {/*    Настройки*/}
                {/*</MenuItem>*/}
                {/*<MenuItem component={'a'} href={paths.dashboard.account} onClick={onClose}>*/}
                {/*    <ListItemIcon>*/}
                {/*        <UserIcon fontSize="var(--icon-fontSize-md)"/>*/}
                {/*    </ListItemIcon>*/}
                {/*    Профиль*/}
                {/*</MenuItem>*/}
                {!user.name ? <MenuItem onClick={() => window.location.replace(paths.auth.signIn)}>
                        <ListItemIcon>
                            <SignInIcon fontSize="var(--icon-fontSize-md)"/>
                        </ListItemIcon>
                        Вход
                    </MenuItem> :
                    <MenuItem onClick={handleSignOut}>
                        <ListItemIcon>
                            <SignOutIcon fontSize="var(--icon-fontSize-md)"/>
                        </ListItemIcon>
                        Выход
                    </MenuItem>
                }
            </MenuList>
        </Popover>
    );
}

function userDescriptor(user) {
    if (!user) {
        return null;
    }
    if (!user.name) {
        return (<Typography variant="subtitle1">Гость</Typography>);
    }
    return (
        <>
            <Typography variant="subtitle1">{user.name + " " + user.lastName}</Typography>
            <Typography color="text.secondary" variant="body2">{user.id}</Typography>
        </>
    );
}
