import Alert from 'Elements/Alert';
import { observer } from 'mobx-react-lite';
import { useStore } from 'stores/hooks';
import styled from 'styled-components';
import { Box, Flex } from 'UIKit/grid';
import titles from '../config/elements-titles';

const Bold = styled.span`
  font-weight: bold;
`;

const Errors = observer(() => {
  const { $calculation } = useStore();

  if (!$calculation.$validation.hasErrors()) {
    return <Alert type="success" showIcon message="Ошибок нет 🙂" />;
  }

  const { elementsErrors } = $calculation.$validation;
  const errors = Object.keys(elementsErrors).map((elementName) => {
    const elementErrors = elementsErrors[elementName];
    const elementTitle = titles[elementName];

    return elementErrors.map((error) => {
      const message = (
        <>
          <Bold>{elementTitle}</Bold>
          {': '}
          {error.text}
        </>
      );

      return <Alert key={error.name} type="error" showIcon message={message} />;
    });
  });

  return <Flex flexDirection="column">{errors}</Flex>;
});

function Validation() {
  return (
    <Box>
      <Errors />
    </Box>
  );
}

export default {
  id: 'validation',
  title: 'Ошибки',
  Component: Validation,
};
