import { store } from '../redux';
import React, { createContext, useContext, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { connect, useSelector } from 'react-redux';

import { AppBar, Box, Toolbar, Typography, Menu, Container, Avatar, Tooltip, MenuItem, IconButton, Stack } from '@mui/material'
import { Instagram, AddAPhotoRounded, Search } from '@mui/icons-material';
// import { actionFullLogout } from '../redux/action';
import { actionFullLogout } from '../redux/thunks';

import { url } from '../../App';


function UserMenu() {
    let history = useHistory()
    const location = useLocation().pathname
    const user = useContext(UserContext)

    // потому что запрос на логин не отдает аватар, а только id и login
    const userData = useSelector(state => state?.promise?.AboutMe?.payload)

    const [anchorElUser, setAnchorElUser] = useState(null)

    // отображение/скрытие меню на аватарке
    const handleOpenUserMenu = (event) => {
        setAnchorElUser(event.currentTarget)
    }
    const handleCloseUserMenu = () => {
        setAnchorElUser(null)
    }

    // Thunk для разлогина и редирект на главную, потому что остальные запросы не работают, если нет токена
    async function onLogout() {

        const result = await store.dispatch(actionFullLogout())

        // проверяем, реально ли очистили токен (и все хранилище)
        if (Object.keys(result).length === 0 && location != '/') {
            history.push('/')
        }
    }


    return (
        <Stack
            direction='row'
        >
            <IconButton
                sx={{
                    color: '#000',
                    transform: 'scale(-1, 1)'
                }}
                onClick={() => {
                    history.push('/search')
                }}
            >
                <Search />
            </IconButton>

            <IconButton
                sx={{
                    color: '#000'
                }}
                onClick={() => {
                    history.push('/createpost')
                }}
            >
                <AddAPhotoRounded />
            </IconButton>

            <Box sx={{ flexGrow: 0 }}>
                <Tooltip>
                    <IconButton
                        onClick={handleOpenUserMenu}
                    >
                        <Avatar
                            alt={user?.login}
                            src={url + userData?.avatar?.url}
                        />
                    </IconButton>
                </Tooltip>

                <Menu
                    sx={{
                        mt: '50px'
                    }}
                    id="menu-appbar"
                    anchorEl={anchorElUser}
                    anchorOrigin={{
                        vertical: 'top',
                        horizontal: 'right',
                    }}
                    keepMounted
                    transformOrigin={{
                        vertical: 'top',
                        horizontal: 'right',
                    }}
                    open={Boolean(anchorElUser)}
                    onClose={handleCloseUserMenu}
                >
                    <MenuItem
                        onClick={() => {
                            history.push(`/user/${user?.id}`)
                        }}
                    >
                        <Typography
                            textAlign="center">
                            <span>
                                {user?.login}
                            </span>
                        </Typography>
                    </MenuItem>

                    <MenuItem
                        onClick={onLogout}
                    >
                        <Typography
                            textAlign="center"
                        >
                            <span>
                                Выйти
                            </span>
                        </Typography>
                    </MenuItem>
                </Menu>
            </Box>
        </Stack>
    )
}


const UserContext = createContext()

function Header({ login }) {
    let history = useHistory()

    function toMain() {
        history.push('/');
    }

    return (
        <AppBar
            position='sticky'
            color='inherit'
        >
            <UserContext.Provider value={login}>
                <Container
                    maxWidth="xl"
                >
                    <Toolbar
                        disableGutters
                    >
                        <Stack
                            direction='row'
                            sx={{
                                display: 'flex',
                                flexGrow: '1'
                            }}
                        >
                            <IconButton
                                edge='start'
                                sx={{
                                    color: '#000'
                                }}
                                onClick={toMain}
                            >
                                <Instagram />

                                <Typography
                                    variant="h6"
                                    sx={{
                                        fontFamily: 'monospace',
                                        fontWeight: 700,
                                        letterSpacing: '.3rem',
                                        ml: 1
                                    }}
                                >
                                    Hipstagram
                                </Typography>
                            </IconButton>
                        </Stack>

                        {/* {login && <UserMenu login={login} />} */}
                        {login && <UserMenu />}

                    </Toolbar>
                </Container>
            </UserContext.Provider>
        </AppBar>
    )
}

export const CHeader = connect(state => ({ login: state?.auth?.payload?.sub }))(Header)