import { HeaderToggleButton, MainCard } from '@/components';
import { Avatar, IconButton, Transitions } from '@/components/@extended';
import { usePopoverState } from '@/hooks';
import { LogoutOutlined } from '@ant-design/icons';
import {
  CardContent,
  ClickAwayListener,
  Grid,
  List,
  Paper,
  Popper,
  Stack,
  Tooltip,
  Typography,
  useTheme
} from '@mui/material';
import { useDataProvider, useGetIdentity, useLogout } from 'ra-core';
import React, { ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
import { ChangePasswordButton, LogoutButton, StopImpersonateButton } from './buttons';

interface HeaderProfileProps {
  roles?: ReactNode;
}

function HeaderProfile(props: HeaderProfileProps) {
  const { roles } = props;
  const theme = useTheme();
  const dataProvider = useDataProvider();
  const { identity } = useGetIdentity();
  const hasProfilePic = identity !== undefined && identity.image && true && identity.image !== '';
  const [profileImage, setProfileImage] = useState<string | null>(null);
  const { open, anchorEl, handleToggle, handleClose } = usePopoverState();
  const logout = useLogout();
  const handleLogout = useCallback(() => {
    // noinspection JSIgnoredPromiseFromCall
    logout();
  }, [logout]);

  useEffect(() => {
    if (hasProfilePic) {
      dataProvider.getFile('/profile/me/image').then((image: string) => setProfileImage(image));
    }
  }, [dataProvider, hasProfilePic]);

  const userRoles = useMemo(
    () =>
      React.isValidElement(roles) ? (
        roles
      ) : roles ? (
        <>{roles}</>
      ) : (
        identity?.roles?.map((r: { name: string }) => r.name.replace('ROLE_', '')).join(',')
      ),
    [roles, identity]
  );

  return (
    <>
      <HeaderToggleButton sx={{ p: 0.25, width: 'auto' }} onClick={handleToggle} value="profile" selected={open}>
        <Stack direction="row" spacing={2} alignItems="center" sx={{ p: 0.5 }}>
          {/** @ts-ignore */}
          <Avatar alt={identity?.name?.toUpperCase()} src={profileImage} size="xs" />
          <Typography variant="subtitle1">{identity?.name}</Typography>
        </Stack>
      </HeaderToggleButton>
      <Popper placement="bottom-end" open={open} anchorEl={anchorEl} role={undefined} transition disablePortal>
        {({ TransitionProps }) => (
          <Transitions type="grow" position="top-right" in={open} {...TransitionProps}>
            <Paper
              sx={{
                // @ts-ignore
                boxShadow: theme.customShadows.z1,
                width: 290,
                minWidth: 240,
                maxWidth: 290,
                [theme.breakpoints.down('md')]: {
                  maxWidth: 250
                },
                marginTop: 1
              }}
            >
              <ClickAwayListener onClickAway={handleClose}>
                <MainCard elevation={0} border={false} content={false}>
                  <CardContent sx={{ px: 2.5, pt: 3 }}>
                    <Grid container justifyContent="space-between" alignItems="center">
                      <Grid item>
                        <Stack direction="row" spacing={1.25} alignItems="center">
                          {/* @ts-expect-error WARN: wtf */}
                          <Avatar alt="profile user" src={profileImage} sx={{ width: 32, height: 32 }} />
                          <Stack>
                            <Typography variant="h6">{identity?.name}</Typography>
                            <Typography variant="body2" color="textSecondary">
                              {userRoles}
                            </Typography>
                          </Stack>
                        </Stack>
                      </Grid>
                      <Grid item>
                        <Tooltip title="Logout">
                          <IconButton size="large" sx={{ color: 'text.primary' }} onClick={handleLogout}>
                            <LogoutOutlined />
                          </IconButton>
                        </Tooltip>
                      </Grid>
                    </Grid>
                  </CardContent>
                  <Grid container>
                    <Grid item xs={12}>
                      <List component="nav" sx={{ p: 0, '& .MuiListItemIcon-root': { minWidth: 32 } }}>
                        <ChangePasswordButton />
                        <LogoutButton />
                        <StopImpersonateButton />
                      </List>
                    </Grid>
                  </Grid>
                </MainCard>
              </ClickAwayListener>
            </Paper>
          </Transitions>
        )}
      </Popper>
    </>
  );
}

export { HeaderProfile };
