import { reaction } from 'mobx';
import type { ReactionsContext } from 'process/types';
import { pick } from 'radash';
import extend from 'stores/tables/insurance/tools';
import message from 'ui/elements/message';

const key = 'KP_LOADING_INFO';

export default function loadKpReactions({ store, trpcClient }: ReactionsContext) {
  const { $calculation, $process, $tables } = store;

  reaction(
    () => $calculation.element('selectQuote').getValue(),
    (quoteId) => {
      if (!quoteId) return;

      $process.add('LoadKP');

      const quoteName = $calculation.element('selectQuote').getOption()?.label;

      message.loading({
        key,
        content: `Загружаем КП ${quoteName}...`,
      });

      const payload = {
        values: {
          quote: quoteId,
          ...pick($calculation.$values.values, ['recalcWithRevision']),
        },
      };

      trpcClient.quote.getData
        .query(payload)
        .then(({ values, payments, insurance, fingap }) => {
          $calculation.$values.setValues({
            values,
            exclude: ['lead', 'opportunity', 'quote', 'leadUrl', 'opportunityUrl', 'quoteUrl'],
          });

          $tables.payments.setValues(payments.values);

          if (insurance.values.osago) {
            extend($tables.insurance).setRowValues(insurance.values.osago);
          }
          if (insurance.values.kasko) {
            extend($tables.insurance).setRowValues(insurance.values.kasko);
          }
          if (insurance.values.fingap) {
            extend($tables.insurance).setRowValues(insurance.values.fingap);
          }

          if (fingap) $tables.fingap.setSelectedKeys(fingap.keys);

          message.success({
            key,
            content: `КП ${quoteName} загружено`,
          });
        })
        .catch(() => {
          message.error({
            key,
            content: `Ошибка во время загрузки КП ${quoteName}`,
          });
        })
        .finally(() => {
          $process.delete('LoadKP');
        });
    }
  );

  reaction(
    () => $process.has('LoadKP'),
    (isLoadKP) => {
      $calculation.$status.setStatus('selectQuote', isLoadKP ? 'Disabled' : 'Default');
    }
  );
}
