import { observer } from 'mobx-react-lite';
import { useStore } from 'stores/hooks';
import styled from 'styled-components';
import Alert from 'ui/elements/Alert';
import { Box, Flex } from 'ui/grid';

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

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

const AlertWrapper = styled(Box)`
  margin: 0 0 5px 0;
`;

function getElementsErrors($calculation) {
  const errors = Object.values($calculation.$validation).map((validation) => {
    const elementErrors = validation.getMessages();
    const elementTitle = validation.params.err_title;

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

  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 hasElementsErrors = Object.values($calculation.$validation).some(
    (validation) => validation.hasErrors
  );
  const hasPaymentsErrors = $tables.payments.validation.hasErrors;
  const hasInsuranceErrors = $tables.insurance.validation.hasErrors;

  if (!hasElementsErrors && !hasPaymentsErrors && !hasInsuranceErrors) {
    return <Alert type="success" showIcon message="Ошибок нет 🙂" />;
  }

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

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

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

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

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