import { alpha, Box, Chip, Typography } from '@mui/material';
import { Icon } from '@iconify/react';
import SwapHorizRoundedIcon from '@iconify-icons/material-symbols/swap-horiz-rounded';
import ArrowRightAltRoundedIcon from '@iconify-icons/material-symbols/arrow-right-alt-rounded';
import { useCreation, useMemoizedFn } from 'ahooks';
import noop from 'lodash/noop';

import DidAvatar from '../../Avatar';
import { getUserAvatar } from '../../Util';
import SessionUserSwitch from './session-user-switch';
import { getWallet } from '../libs/utils';
import { translations } from '../libs/translation';
import { translate } from '../../Locale/util';
import type { $TSFixMe, Locale, Session } from '../../type';

export interface UserInfoProps {
  session: Session;
  onSwitchPassport: () => void;
  onSwitchAccount: (params?: { userSession: Session }) => void;
  onBindWallet: () => void;
  onSwitchProfile?: () => void;
  locale?: Locale;
  isBlocklet?: true | false;
}

export default function UserInfo({
  session,
  onSwitchPassport,
  onSwitchAccount,
  onBindWallet,
  onSwitchProfile = noop,
  locale = 'en',
  isBlocklet = true,
}: UserInfoProps) {
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });
  const avatar = getUserAvatar(session.user?.avatar?.replace(/\s/g, encodeURIComponent(' ')), 64);
  const currentRole = useCreation(() => {
    // FIXME: @zhanghan 感觉应该把 name 的判断去掉？
    return session.user?.passports?.find(
      (item: $TSFixMe) => item.name === session.user.role || item.role === session.user.role
    );
  }, [session?.user?.passports, session?.user?.role]);

  const hasBindWallet = useCreation(() => {
    return getWallet(session?.user);
  }, [session?.user]);

  return (
    <Box
      sx={{
        py: 2,
        px: 0.5,
        pb: 1,
        display: 'flex',
        flexDirection: 'column',
        gap: 1.5,
      }}>
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          gap: 1,
          px: 2,
        }}>
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 1.5,
          }}>
          <Box
            onClick={isBlocklet ? noop : onSwitchProfile}
            data-cy="sessionManager-switch-profile-trigger"
            sx={{
              cursor: isBlocklet ? 'default' : 'pointer',
              position: 'relative',
              borderRadius: '100%',
              overflow: 'hidden',
              fontSize: 0,
              flexShrink: 0,
              '&:hover': isBlocklet
                ? {}
                : {
                    '&::after': {
                      content: `"${t('switch')}"`,
                      position: 'absolute',
                      bottom: 0,
                      background: 'rgba(0, 0, 0, 0.2)',
                      left: 0,
                      right: 0,
                      height: '2.2em',
                      color: 'white',
                      textAlign: 'center',
                      fontSize: '12px',
                      lineHeight: '2em',
                    },
                  },
            }}>
            <DidAvatar
              variant="circle"
              did={session.user.did}
              src={avatar}
              size={48}
              shape="circle"
              sx={{
                cursor: isBlocklet ? 'unset' : 'pointer',
              }}
            />
          </Box>

          <Typography variant="h6" sx={{ wordBreak: 'break-word' }}>
            {session.user.fullName}
          </Typography>
        </Box>
        <Chip
          label={currentRole?.title || session.user?.role.toUpperCase()}
          size="small"
          variant="outlined"
          clickable
          sx={{
            flexShrink: 0,
            fontWeight: 'bold',
            fontSize: '12px',
            color: 'text.primary',
            borderColor: 'grey.100',
            pr: 1,
            pl: 0.5,
            '&:active': {
              boxShadow: 'none',
            },
          }}
          deleteIcon={<Icon icon={SwapHorizRoundedIcon} color="inherit" />}
          onDelete={onSwitchPassport}
          onClick={onSwitchPassport}
          data-cy="sessionManager-switch-passport-trigger"
        />
      </Box>
      <SessionUserSwitch session={session} onSwitch={onSwitchAccount} isBlocklet={isBlocklet} locale={locale} />
      {!hasBindWallet ? (
        <Box
          sx={{
            color: 'secondary.main',
            bgcolor: ({ palette }) => alpha(palette.secondary.main, 0.05),
            borderRadius: 1,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            fontSize: 12,
            py: 0.75,
            px: 1.5,
            cursor: 'pointer',
            mt: -0.75,
          }}
          onClick={onBindWallet}
          data-cy="sessionManager-bind-trigger">
          {t('connectDIDWallet')}
          <Icon icon={ArrowRightAltRoundedIcon} color="inherit" fontSize={16} />
        </Box>
      ) : null}
    </Box>
  );
}
