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

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

const TableWrapper = styled.div`
  td > * {
    margin: 0;
  }
`;

const TablesGroupGrid = styled(Box)`
  display: flex;
  flex-direction: column;
  gap: 10px;

  ${min('tablet')} {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
  }
`;

const Validation = observer(() => {
  const store = useStore();
  const { payments } = store.$tables;

  const messages = payments.validation.getMessages();

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

  return null;
});

const SPLIT_NUMBER = 12;

function TablePart({ num }) {
  const store = useStore();
  const { payments } = store.$tables;

  const values = payments.values.slice(num * SPLIT_NUMBER, num * SPLIT_NUMBER + SPLIT_NUMBER);

  const dataSource = values.map((value, index) => ({
    key: index + num * SPLIT_NUMBER,
    num: index + num * SPLIT_NUMBER,
    paymentRelation: value,
  }));

  return (
    <TableWrapper>
      <Table size="small" columns={columns} dataSource={dataSource} pagination={false} />
    </TableWrapper>
  );
}

const TablesGroup = observer(() => {
  const store = useStore();
  const { payments } = store.$tables;

  const valuesLength = computed(() => payments.values.length).get();

  const tablesNumber = Math.ceil(valuesLength / SPLIT_NUMBER);

  const tables = [];
  for (let i = 0; i < tablesNumber; i += 1) {
    tables.push(<TablePart key={i} num={i} />);
  }

  return <TablesGroupGrid>{tables}</TablesGroupGrid>;
});

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