/* eslint-disable sonarjs/cognitive-complexity */
import { PolicyTable, ReloadButton, Validation } from './Components';
import { columns } from './lib/config';
import { makeEltOsagoRequest } from './lib/make-request';
import type { Row, StoreSelector } from './types';
import { getEltOsago } from '@/api/elt/query';
import { STALE_TIME } from '@/constants/request';
import { 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 type { QueryFunctionContext } from '@tanstack/react-query';
import { useQueries } from '@tanstack/react-query';
import { observer } from 'mobx-react-lite';
import { Flex } from 'ui/grid';

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

const initialData = {
  ...defaultRow,
  error: null,
  premiumSum: 0,
  sum: 0,
};

export const Osago = observer(() => {
  const store = useStore();
  const { $tables } = store;

  const apolloClient = useApolloClient();

  const { init } = helper({ apolloClient, store });

  const queries = useQueries({
    queries: $tables.elt.osago.getRows.map((row) => {
      const { id, key, name } = row;

      return {
        cacheTime: 0,
        enabled: false,
        initialData: { ...initialData, id, key, name },
        queryFn: async (context: QueryFunctionContext) => {
          const payload = await makeEltOsagoRequest({ apolloClient, store }, row);
          const res = await getEltOsago(payload, context);

          if (res) {
            const companyRes = res?.[id];

            return { ...companyRes, id, key, name };
          }

          return { ...initialData, id, key, name };
        },
        queryKey: ['elt', 'osago', id],
        refetchOnWindowFocus: false,
        retry: false,
        staleTime: STALE_TIME,
      };
    }),
  });

  async function handleOnClick() {
    const { osago } = await init();
    $tables.elt.osago.setRows(osago);

    const osagoCompanyIds = $tables.insurance
      .row('osago')
      .getOptions('insuranceCompany')
      .map((x) => x.value);

    queries
      .filter(({ data }) => data?.key && osagoCompanyIds.includes(data?.key))
      .forEach(({ refetch, data }) => {
        if (data?.key) $tables.elt.osago.setRow({ key: data?.key, status: 'fetching' });

        refetch()
          .then((res) => {
            if (res.data) {
              const { key, numCalc, premiumSum = 0, message, skCalcId } = res.data;
              let { error } = res.data;

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

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

              $tables.elt.osago.setRow({
                key,
                message: error || message,
                numCalc,
                skCalcId,
                status: error ? 'error' : null,
                sum: premiumSum,
              });
            }
          })
          .catch((error) => {
            if (data?.key)
              $tables.elt.osago.setRow({
                ...defaultRow,
                key: data?.key,
                message: error,
                status: 'error',
              });
          });
      });
  }

  function handleOnSelectRow(row: Row) {
    $tables.insurance.row('osago').column('insuranceCompany').setValue(row.key);
    $tables.insurance.row('osago').column('insCost').setValue(row.sum);
  }

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

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

    if (column.key === 'totalFranchise') {
      return {
        ...column,
        render: () => 'Не требуется',
      };
    }

    return column;
  });

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