import { useRef } from 'react';
import {
  Box,
  type BoxProps,
  ClickAwayListener,
  Fade,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  Paper,
  Popper,
  Typography,
  useTheme,
} from '@mui/material';
import { Icon } from '@iconify/react';
import DashboardOutlineRoundedIcon from 'iconify-icons-material-symbols-400/dashboard-outline-rounded';
import WidgetsOutlineRoundedIcon from '@iconify-icons/material-symbols/widgets-outline-rounded';
import { useMemoizedFn, useReactive } from 'ahooks';

import Button from '../Button';
import { BLOCKLET_SERVICE_PATH_PREFIX, NAVIGATION_URL } from '../Util/constant';
import SessionPermission from '../SessionPermission';
import { getTranslation } from '../Util';
import type { Locale } from '../type';

export interface SessionBlockletProps extends Omit<BoxProps, 'onClick' | 'onMouseEnter' | 'onMouseLeave'> {
  session: Record<string, any>;
  locale?: Locale;
  size?: number;
  popperType?: 'hover' | 'click';
}

export default function SessionBlocklet({
  session,
  locale = 'zh',
  size = 24,
  popperType = 'click',
  sx,
  ...rest
}: SessionBlockletProps) {
  const blocklet = window?.blocklet || {};
  const sessionMenuList = (blocklet.navigation || [])
    // HACK 过滤掉默认插入的 /sessionManager 菜单
    .filter((item) => item.section === 'sessionManager' && !['/sessionManager'].includes(item.id))
    .filter((item) => {
      if ((item?.role || []).includes(session?.user?.role || 'guest')) {
        return true;
      }
      return false;
    })
    .map((item) => {
      const component = (blocklet?.componentMountPoints || []).find((x) => item.component === x.name);
      return {
        ...item,
        component,
      };
    });
  const theme = useTheme();
  const popperAnchorRef = useRef(null);
  const currentState = useReactive({
    open: false,
  });
  const onTogglePopper = useMemoizedFn((value = !currentState.open) => {
    currentState.open = value;
  });
  const handleEventProps =
    popperType === 'hover'
      ? { onMouseEnter: () => onTogglePopper(true), onMouseLeave: () => onTogglePopper(false) }
      : { onClick: () => onTogglePopper() };

  if (sessionMenuList.length === 0 || !session?.user) {
    return null;
  }

  return (
    <Box
      sx={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', ...sx }}
      {...rest}
      {...handleEventProps}>
      <IconButton size="medium" ref={popperAnchorRef}>
        <Icon icon={DashboardOutlineRoundedIcon} fontSize={size} style={{ transform: 'scale(1.08)' }} />
      </IconButton>
      <Popper
        open={currentState.open}
        anchorEl={popperAnchorRef.current}
        transition
        placement="bottom-end"
        sx={{ zIndex: 1600 }}>
        {({ TransitionProps }) => (
          <ClickAwayListener
            onClickAway={(e) => {
              e.preventDefault();
              e.stopPropagation();
              onTogglePopper(false);
            }}>
            <Fade {...TransitionProps} timeout={350}>
              <Paper
                variant="outlined"
                sx={{
                  borderRadius: 1.5,
                  width: 350,
                  maxWidth: '90vw',
                  p: 2,
                }}>
                <List
                  sx={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(auto-fill, 100px)',
                    gridAutoRows: 'minmax(100px, max-content)',
                    justifyContent: 'space-between',
                    maxHeight: 350,
                    overflowY: 'auto',
                    p: 0,
                  }}>
                  {sessionMenuList.map((item) => (
                    <ListItem key={item.id} disablePadding>
                      <ListItemButton
                        href={getTranslation(item.link, locale)}
                        sx={{
                          p: 1,
                          display: 'flex',
                          flexDirection: 'column',
                          alignItems: 'center',
                          gap: 1,
                          width: '100%',
                          height: '100%',
                          borderRadius: 1,
                          '&:hover': {
                            backgroundColor: 'action.hover',
                          },
                        }}>
                        {item?.component?.did ? (
                          <Box
                            component="img"
                            src={`${BLOCKLET_SERVICE_PATH_PREFIX}/blocklet/logo-bundle/${item.component.did}`}
                            sx={{
                              borderRadius: 1,
                              width: 50,
                              height: 50,
                              objectFit: 'contain',
                            }}
                            alt="SessionBlocklet component icon"
                          />
                        ) : (
                          <Icon
                            fontSize={50}
                            icon={item.icon || WidgetsOutlineRoundedIcon}
                            color={theme.palette.text.secondary}
                          />
                        )}

                        <Typography
                          sx={{
                            fontSize: '12px',
                            color: 'text.primary',
                            textAlign: 'center',
                            lineHeight: 'normal',
                          }}>
                          {getTranslation(item.title, locale)}
                        </Typography>
                      </ListItemButton>
                    </ListItem>
                  ))}
                </List>
                <SessionPermission session={session}>
                  <Button variant="outlined" fullWidth href={NAVIGATION_URL} sx={{ mt: 1 }}>
                    {locale === 'zh' ? '管理' : 'Manage'}
                  </Button>
                </SessionPermission>
              </Paper>
            </Fade>
          </ClickAwayListener>
        )}
      </Popper>
    </Box>
  );
}
