/* eslint-disable react/jsx-key */
import { useStore } from '@/stores/hooks';
import { observer } from 'mobx-react-lite';
import styled from 'styled-components';
import { Alert } from 'ui/elements';
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 getAlerts(errors, title, $process) {
  return errors.map(({ key, message }) => (
    <AlertWrapper>
      <Alert
        key={key}
        type={$process.has('Unlimited') ? 'warning' : 'error'}
        showIcon
        message={Message(title, message)}
      />
    </AlertWrapper>
  ));
}

function getElementsErrors({ $calculation, $process }) {
  return Object.values($calculation.$validation).map((validation) => {
    const elementErrors = validation.getErrors();
    const elementTitle = validation.params.err_title;

    return getAlerts(elementErrors, elementTitle, $process);
  });
}

function getTableErrors(tableName, { $process, $tables }) {
  const table = $tables[tableName];
  const errors = table.validation.getErrors();
  const title = table.validation.params.err_title;

  return getAlerts(errors, title, $process);
}

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

  const hasElementsErrors = Object.values($calculation.$validation).some(
    (validation) => validation.hasErrors
  );
  const hasPaymentsErrors = $tables.payments.validation.hasErrors;
  const hasInsuranceErrors = $tables.insurance.validation.hasErrors;
  const hasFingapErrors = $tables.fingap.validation.hasErrors;

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

  const elementsErrors = getElementsErrors(store);
  const paymentsErrors = getTableErrors('payments', store);
  const insuranceErrors = getTableErrors('insurance', store);
  const fingapErrors = getTableErrors('fingap', store);

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

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

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

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