import { Box, type BoxProps, IconButton, Tooltip, Typography, useTheme } from '@mui/material';
import { Icon } from '@iconify/react';
import LensIcon from '@iconify-icons/material-symbols/lens';

import WalletOSIcon from '../../WalletOSIcon';
import Avatar from '../../Avatar';
import { DID } from '../../DID';
import { getSourceProvider } from '../libs/utils';
import { Session } from '../../type';

export interface SessionUserItemProps extends BoxProps {
  sessionItem: Session;
  statusContent?: React.ReactNode;
  active?: false | true;
}

function SessionUserItem({
  ref = undefined,
  sessionItem,
  statusContent = null,
  active = false,
  ...rest
}: SessionUserItemProps & {
  ref?: React.Ref<unknown>;
}) {
  const { palette } = useTheme();
  const isRawWalletAccount = getSourceProvider(sessionItem?.user) === 'wallet';

  return (
    <Box
      {...rest}
      ref={ref}
      sx={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        py: 0.75,
        px: 1,
        width: '100%',
        ...rest?.sx,
      }}>
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          gap: 0.5,
          overflow: 'hidden',
          '& .did-address-avatar': {
            display: 'none !important',
          },
        }}>
        <Box sx={{ mr: 0.5, fontSize: 0 }}>
          <Avatar did={sessionItem.userDid} size={36} />
        </Box>
        <WalletOSIcon
          color={palette.text.secondary}
          loading={sessionItem.__isDefault}
          provider={sessionItem?.extra?.provider}
          walletOS={sessionItem?.extra?.walletOS}
        />
        {isRawWalletAccount ? (
          <DID did={sessionItem.userDid} copyable={false} size={14} responsive={false} compact sx={{ lineHeight: 1 }} />
        ) : (
          sessionItem.user.email && (
            <Tooltip
              title={sessionItem.user.email}
              sx={{
                zIndex: 1600,
              }}
              placement="top">
              <Typography
                sx={{
                  fontSize: 14,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}>
                {sessionItem.user.email}
              </Typography>
            </Tooltip>
          )
        )}
      </Box>
      {statusContent ||
        (active && (
          <IconButton size="small" disableRipple>
            <Icon icon={LensIcon} fontSize={6} color={palette.success.main} />
          </IconButton>
        ))}
    </Box>
  );
}

export default SessionUserItem;
