import { useState } from 'react';
import { useMemoizedFn } from 'ahooks';
import { MenuItem, BoxProps, Divider, useTheme } from '@mui/material';
import { Icon } from '@iconify/react';
import LensIcon from '@iconify-icons/material-symbols/lens';
import { Locale, Session } from '../../type';
import { translate } from '../../Locale/util';
import { translations } from '../libs/translation';
import { DID_SPACE_URL } from '../../Util/constant';
import { TBox } from '../../MuiWrap';
import Typography from '../../Typography';
import DIDLogo from '../../DIDLogo';

export interface DidSpaceProps extends BoxProps {
  session: Session;
  locale?: Locale;
}

export default function DidSpace({ session, locale = 'en', ...rest }: DidSpaceProps) {
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });
  const theme = useTheme();

  const didSpace = session.user?.didSpace ?? {};
  const [offset, setOffset] = useState(0);
  const onShrink = useMemoizedFn(({ fontSize, initialSize }: { fontSize: number; initialSize: number }) => {
    setOffset(Math.ceil((initialSize - fontSize) / 4));
  });

  return (
    <>
      <TBox component="a" href={DID_SPACE_URL} sx={{ p: 0.5, display: 'block', textDecoration: 'none' }} {...rest}>
        <MenuItem
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 0.5,
            py: 1,
          }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <DIDLogo name="spaces" size={20} dark={theme.palette.mode === 'dark'} fontSize={40} />
          </div>
          <span style={{ color: theme.palette.text.secondary }}>:</span>
          <div
            style={{
              flexGrow: 1,
              minWidth: 0,
              color: didSpace.did ? theme.palette.text.primary : theme.palette.text.secondary,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
            }}>
            <Typography fontSize="auto" minFontSize={1} sx={{ marginTop: `${offset}px` }} onShrink={onShrink}>
              {didSpace.did ? didSpace.name : t('disconnected')}
            </Typography>
          </div>
          <Icon
            style={{ marginTop: `${offset}px`, flexShrink: 0 }}
            icon={LensIcon}
            fontSize={8}
            color={didSpace.did ? theme.palette.success.main : theme.palette.grey[200]}
          />
        </MenuItem>
      </TBox>
      <Divider />
    </>
  );
}
