import Alert from 'elements/Alert';
import Table from 'elements/Table';
import { toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import { useStore } from 'stores/hooks';
import styled from 'styled-components';
import { Flex } from 'ui/grid';
import { columns } from './config';

const Grid = styled(Flex)`
  flex-direction: column;
`;

const Validation = observer(() => {
  const store = useStore();

  const messages = store.$tables.fingap.validation.getMessages();

  if (messages?.length) {
    return <Alert type="error" banner message={messages[0]} />;
  }

  return null;
});

const FinGAPTable = observer(() => {
  const { $tables } = useStore();
  const { fingap } = $tables;

  const dataSource = toJS(fingap.risks);
  const selectedRowKeys = [...toJS(fingap.selectedKeys)];

  return (
    <Table
      columns={columns}
      dataSource={dataSource}
      rowSelection={{
        type: 'checkbox',
        onChange: (_, selectedRows) => {
          const selectedKeys = selectedRows.reduce((acc, row) => {
            acc.push(row.key);
            if (row.keys) return [...acc, ...row.keys];

            return acc;
          }, []);

          fingap.setSelectedKeys(selectedKeys);
        },
        selectedRowKeys,
      }}
      pagination={false}
      size="small"
      scroll={{
        x: true,
      }}
    />
  );
});

export default function () {
  return (
    <Grid>
      <Validation />
      <FinGAPTable />
    </Grid>
  );
}
