import React from 'react';
import Avatar from '@mui/material/Avatar';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import { Error as ErrorIcon } from '@mui/icons-material';
import Suite from './Suite';
import Summary from './Summary';
import { red } from '@mui/material/colors';

const TestResults = ({ results, lang }) => {
  const handleRef = (el) => {
    if (!el || !results) {
      return;
    }

    // If results are not recent (within 2 seconds) we do not focus as we do not
    // consider de render as the result of clicking the button tu run the tests.
    if (
      !(results instanceof Error)
      && Date.now() - new Date(results.stats.end) > 2 * 1000
    ) {
      return;
    }

    el.scrollIntoView({
      behavior: 'smooth',
      block: 'end',
    });
  };

  return (
    <List ref={handleRef}>
      {results instanceof Error
        ? (
          <ListItem>
            <Avatar
              sx={theme => ({
                backgroundColor: red[500],
                marginRight: theme.spacing(1),
              })}
            >
              <ErrorIcon />
            </Avatar>
            <ListItemText primary={results.message} />
          </ListItem>
        )
        : (
          <>
            {results.suite && (
              <Suite suite={results.suite} />
            )}
            <Summary stats={results.stats} lang={lang} />
          </>
        )}
    </List>
  );
};

export default TestResults;
