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 '../Calculation/config/elements-titles';

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

function Message(title, text) {
  return (
    <>
      <Bold>{title}</Bold>
      {': '}
      {text}
    </>
  );
}

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

    return elementErrors.map((error) => (
      <Alert key={error.name} type="error" showIcon message={Message(elementTitle, error.text)} />
    ));
  });

  return errors;
}

function getPaymentsTableErrors($tables) {
  const { payments } = $tables;
  const messages = payments.validation.getMessages();
  const title = payments.validation.params.err_title;

  return messages.map((text) => <Alert type="error" showIcon message={Message(title, text)} />);
}

function getInsuranceTableErrors($tables) {
  const { insurance } = $tables;
  const messages = insurance.validation.getMessages();

  return messages.map((message) => <Alert type="error" showIcon message={message} />);
}

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

  const elementsErrors = getElementsErrors($calculation);
  const paymentsErrors = getPaymentsTableErrors($tables);
  const insuranceErrors = getInsuranceTableErrors($tables);

  const errors = [...elementsErrors, ...paymentsErrors, ...insuranceErrors];

  if (errors.length === 0) return <Alert type="success" showIcon message="Ошибок нет 🙂" />;

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

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

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