import React, { useState, useMemo } from 'react';
import { fireEvent } from '@testing-library/react';
import { render } from '~/testUtils/helpers';
import { Table } from '..';
import { TextInput } from '~/components/TextInput';

describe('<Table/>', () => {
  it('allows to edit correct value of 2nd row after deleting 1st row', () => {
    interface Row {
      identity: string;
    }

    let updateDataCalled = false;

    const WrapperComponent = () => {
      const initialData = (count: number): Row[] =>
        Array.from({ length: count }).map((e, i) => ({
          identity: `0x${i}`,
        }));

      const [data, setData] = useState(initialData(2));
      const columns = useMemo(
        () => [
          {
            Header: 'uniqueValue',
            columns: [
              {
                Header: 'Identity',
                accessor: 'identity',
                editor: TextInput,
              },
            ],
          },
        ],
        [data]
      );

      const updateData = (newData: Row[]) => {
        updateDataCalled = true;
        expect(newData).toStrictEqual([
          {
            identity: '0x1edited',
          },
        ]);
        setData(newData);
      };

      const deleteRow = (rowData: Row) => {
        setData(data.filter((entry) => entry.identity !== rowData.identity));
      };

      return (
        <Table
          columns={columns}
          data={data}
          deleteRow={deleteRow}
          updateData={updateData}
        />
      );
    };

    const { container, getByText } = render(<WrapperComponent />);
    expect(container).toBeDefined();

    let tableRows = container.querySelectorAll('tbody tr');

    expect(tableRows.length).toBe(2);

    expect(tableRows[0].querySelector('td')?.textContent).toBe('0x0');
    expect(tableRows[1].querySelector('td')?.textContent).toBe('0x1');

    const deleteFirstRowEl = tableRows[0].querySelector('.showOnHover');

    if (deleteFirstRowEl) {
      fireEvent.click(deleteFirstRowEl);
    }

    tableRows = container.querySelectorAll('tbody tr');
    expect(tableRows.length).toBe(1);
    expect(tableRows[0].querySelector('td')?.textContent).toBe('0x1');

    fireEvent.click(getByText('0x1'));

    const identityEditor = container.querySelector('tbody tr input');

    expect(identityEditor?.getAttribute('value')).toBe('0x1');

    if (identityEditor) {
      fireEvent.change(identityEditor, {
        target: { value: '0x1edited' },
      });
    }

    expect(identityEditor?.getAttribute('value')).toBe('0x1edited');
    expect(updateDataCalled).toBe(false);

    if (identityEditor) {
      fireEvent.blur(identityEditor);
    }

    expect(tableRows[0].querySelector('td')?.textContent).toBe('0x1edited');
    expect(updateDataCalled).toBe(true);
  });
});
