/* eslint-disable sonarjs/cognitive-complexity */
import { PolicyTable, ReloadButton, Validation } from './Components';
import { columns } from './lib/config';
import { makeEltKaskoRequest } from './lib/make-request';
import type { Row, StoreSelector } from './types';
import { getEltKasko } from '@/api/elt/query';
import { MAX_FRANCHISE, MAX_INSURANCE, MIN_INSURANCE } from '@/constants/values';
import helper from '@/process/elt/lib/helper';
import { useStore } from '@/stores/hooks';
import { defaultRow } from '@/stores/tables/elt/default-values';
import { useApolloClient } from '@apollo/client';
import { observer } from 'mobx-react-lite';
import { omit, sift } from 'radash';
import { useCallback } from 'react';
import { Flex } from 'ui/grid';

const storeSelector: StoreSelector = ({ kasko }) => kasko;

const initialData = {
  ...omit(defaultRow, ['name', 'key', 'id']),
  error: null,
  kaskoSum: 0,
  paymentPeriods: [
    {
      kaskoSum: 0,
    },
  ],
};

export const Kasko = observer(() => {
  const store = useStore();
  const { $tables, $calculation } = store;
  const apolloClient = useApolloClient();
  const { init } = helper({ apolloClient, store });

  const handleOnClick = useCallback(async () => {
    $tables.elt.kasko.abortController?.abort();
    $tables.elt.kasko.abortController = new AbortController();

    const { kasko } = await init();
    $tables.elt.kasko.setRows(kasko);
    const kaskoCompanyIds = sift(
      $tables.insurance
        .row('kasko')
        .getOptions('insuranceCompany')
        .map((x) => x.value)
    );
    const values = $calculation.$values.getValues();

    kaskoCompanyIds.forEach((key) => {
      const row = $tables.elt.kasko.getRow(key);
      if (row) {
        $tables.elt.kasko.setRow({ key, status: 'fetching' });
        makeEltKaskoRequest({ apolloClient, store }, row)
          .then((payload) =>
            getEltKasko(payload, { signal: $tables.elt.kasko.abortController?.signal })
          )
          .then((res) => {
            if (res) {
              const {
                kaskoSum = 0,
                message,
                skCalcId,
                totalFranchise = 0,
                requestId,
                paymentPeriods,
              } = res;
              let { error } = res;

              if (totalFranchise > MAX_FRANCHISE) {
                error ||= `Франшиза по страховке превышает максимально допустимое значение: ${Intl.NumberFormat(
                  'ru',
                  {
                    currency: 'RUB',
                    style: 'currency',
                  }
                ).format(MAX_FRANCHISE)}`;
              }

              if (kaskoSum > MAX_INSURANCE) {
                error ||= `Сумма по страховке превышает максимально допустимое значение по стоимости КАСКО: ${Intl.NumberFormat(
                  'ru',
                  {
                    currency: 'RUB',
                    style: 'currency',
                  }
                ).format(MAX_INSURANCE)}`;
              }

              if (kaskoSum < MIN_INSURANCE) {
                error ||= `Сумма по страховке не должна быть меньше допустимого значения по стоимости КАСКО: ${Intl.NumberFormat(
                  'ru',
                  {
                    currency: 'RUB',
                    style: 'currency',
                  }
                ).format(MIN_INSURANCE)}`;
              }

              $tables.elt.kasko.setRow({
                key,
                message: error || message,
                numCalc: 0,
                requestId,
                skCalcId,
                status: error ? 'error' : null,
                sum: values.leasingPeriod <= 16 ? kaskoSum : paymentPeriods?.[0]?.kaskoSum || 0,
                totalFranchise,
              });
            }
          })
          .catch((error) => {
            const _err = error as Error;
            $tables.elt.kasko.setRow({
              ...initialData,
              key,
              message: _err.message || String(error),
              status: 'error',
            });
          });
      }
    });
  }, [$calculation.$values, $tables.elt.kasko, $tables.insurance, apolloClient, init, store]);

  function handleOnSelectRow(row: Row) {
    $tables.insurance.row('kasko').column('insuranceCompany').setValue(row.key);
    $tables.insurance.row('kasko').column('insCost').setValue(row.sum);
    $calculation.element('tbxInsFranchise').setValue(row.totalFranchise);
  }

  type Column = (typeof columns)[number];
  const kaskoColumns = columns.map((column: Column) => {
    if (column.key === 'name') {
      return {
        ...column,
        title: 'Страховая компания КАСКО',
      };
    }

    if (column.key === 'status') {
      return {
        ...column,
        title: <ReloadButton storeSelector={storeSelector} onClick={() => handleOnClick()} />,
      };
    }

    return column;
  });

  return (
    <Flex flexDirection="column">
      <Validation storeSelector={storeSelector} />
      <PolicyTable
        storeSelector={storeSelector}
        columns={kaskoColumns}
        onSelectRow={(row) => handleOnSelectRow(row)}
      />
    </Flex>
  );
});
