/* eslint-disable sonarjs/cognitive-complexity */
import { PolicyTable, ReloadButton, Validation } from './Components';
import { columns } from './lib/config';
import { resetRow } from './lib/tools';
import type { Row, StoreSelector } from './types';
import { useStore } from '@/stores/hooks';
import { trpcClient } from '@/trpc/client';
import { observer } from 'mobx-react-lite';
import { Flex } from 'ui/grid';

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

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

  const calculateKasko = trpcClient.eltKasko.useMutation({
    onError() {
      $tables.elt.kasko.setRows(
        $tables.elt.kasko.getRows.map((row) => ({ ...row, status: 'error' }))
      );
    },
    onMutate: () => {
      const rows = $tables.elt.kasko.getRows;
      $tables.elt.kasko.setRows(rows.map((row) => ({ ...resetRow(row), status: 'fetching' })));
    },
    onSuccess: ({ rows }) => {
      $tables.elt.kasko.setRows(rows);
    },
  });

  function handleOnClick() {
    calculateKasko.mutate({
      calculation: {
        values: store.$calculation.$values.getValues(),
      },
    });
  }

  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>
  );
});
