import { Box, IconButton, SxProps, Tooltip } from '@mui/material';
import CheckIcon from '@iconify-icons/material-symbols/check';
import { Icon } from '@iconify/react';
import { useCreation, useSize } from 'ahooks';
import { useRef } from 'react';

import { DID } from '../DID';
import { mergeSx } from '../Util/style';
import AppIcon from './app-icon';
import { DID_CONNECT_MEDIUM_WIDTH } from '../Util/constant';

export default function AppInfoItem({
  appInfo,
  active = false,
  appLogo = null,
  sx = {},
}: {
  appInfo: any;
  active?: boolean;
  appLogo?: React.ReactNode;
  sx?: SxProps;
}) {
  const rootRef = useRef<HTMLDivElement>(null);
  const size = useSize(rootRef);
  const isTinyView = useCreation(() => {
    if (size) {
      return size.width < DID_CONNECT_MEDIUM_WIDTH - 50;
    }
    return true;
  }, [size, size?.width]);

  return (
    <Box
      ref={rootRef}
      sx={mergeSx(
        {
          display: 'flex',
          alignItems: 'center',
          fontWeight: 600,
          color: 'text.primary',

          '& .app-info-content': {
            paddingLeft: '8px',
            overflow: 'hidden',
          },

          '& .app-info-name': {
            maxWidth: '100%',
            lineHeight: 'normal',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            fontSize: '12px',
            color: 'text.primary',
          },
        },
        sx
      )}>
      {appLogo || (
        <Box
          sx={{
            borderRadius: 1,
            overflow: 'hidden',
            fontSize: 0,
          }}>
          <AppIcon appInfo={appInfo} />
        </Box>
      )}

      <Box className="app-info-content">
        <Tooltip title={appInfo.appName} placement="top">
          <Box className="app-info-name">{appInfo.appName}</Box>
        </Tooltip>
        {appInfo.appPid && (
          <DID
            className="app-info-did"
            did={appInfo.appPid}
            sx={{ fontSize: '10px !important' }}
            copyable={false}
            startChars={isTinyView ? 6 : 8}
            endChars={isTinyView ? 6 : 8}
            size={12}
          />
        )}
      </Box>
      {active ? (
        <IconButton size="small" color="success">
          <Icon icon={CheckIcon} color="success" />
        </IconButton>
      ) : null}
    </Box>
  );
}
