/* eslint-disable no-negated-condition */
/* 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 = ({ osago }) => osago;

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

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

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

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