import pluralize from 'pluralize';

import InfoIcon from '@mui/icons-material/InfoOutlined';
import { Box, Tooltip, Typography } from '@mui/material';

import { darkBlue, gray, orange } from '../../../themes/common';
import type { Theme } from '@mui/material';
import type { GroupStats } from '../types';
import { OsPieChart } from './OsPieChart';

interface GroupStatisticsProps {
  // Whether rowCount comes from a finished query; exposed as data-loaded so
  // Selenium can tell a real 0 from a query that has not answered yet.
  loaded: boolean;
  rowCount: number;
  stats: GroupStats;
}

const hostsCountSx = (theme: Theme) => ({
  color: theme.palette.mode === 'dark' ? orange[800] : darkBlue[400],
  mb: '24px',
  mt: 1
});

export const GroupStatistics = ({ loaded, rowCount, stats }: GroupStatisticsProps) => (
  <Box sx={{ display: 'flex', gap: 4, alignItems: 'center', flexWrap: 'wrap' }}>
    <Box sx={{ flex: '0 0 610px', maxWidth: '100%', minWidth: 0 }}>
      <Box sx={{ display: 'flex', alignItems: 'center' }}>
        <Typography variant="h2">
          Number of hosts
        </Typography>
        <Tooltip title="Hosts in this group can change dynamically as reporting data changes.">
          <InfoIcon fontSize="small" sx={{ color: gray[500], ml: 2 }} />
        </Tooltip>
      </Box>
      <Typography data-testid="group-hosts-count" data-loaded={loaded ? 'true' : 'false'} variant="statValue" sx={hostsCountSx}>
        {pluralize('host', rowCount, true)}
      </Typography>
      {rowCount > 0 && (
        <Box sx={{ display: 'flex', flexWrap: 'wrap' }}>
          <Typography variant="subtitle2" sx={{ mb: 1, mr: 2 }}>
            OS: {stats.os.join(', ')}
          </Typography>
          <Typography variant="subtitle2">CFEngine versions: {stats.versions.join(', ')}</Typography>
        </Box>
      )}
    </Box>
    {rowCount > 0 && (
      <Box sx={{ width: 450, maxWidth: '100%', height: 155 }}>
        <OsPieChart distribution={stats.osDistribution} />
      </Box>
    )}
  </Box>
);
