import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';

import { TABLE_HEADERS } from '../../../constants';

import * as selectors from '../../../redux/selectors';
import { getDataAction, setTableAction, updateContentOwner } from '../../../redux/slices';
import { omitUndefinedProps } from '@/mui/helpers';

import CommonTable from '@/modules/@common/Table';
import Row from './components/Row/Row';

import styles from './ContentTab.module.scss';

function Table() {
  const dispatch = useDispatch();
  const router = useRouter();

  const [editRowData, setEditRowData] = useState({
    id: null,
    salesforceId: null,
    status: null,
    isPublic: null,
    comments: null,
    callToAction: null,
  });

  const data = useSelector(selectors.dataSelector);
  const page = useSelector(selectors.pageSelector);
  const pageSize = useSelector(selectors.pageSizeSelector);
  const totalCount = useSelector(selectors.totalCountSelector);
  const sortBy = useSelector(selectors.sortBySelector);
  const sortOrder = useSelector(selectors.sortOrderSelector);

  const { id } = router.query;

  const handleFilter = (filter) => {
    const { page: page$, pageSize: pageSize$ } = filter;

    dispatch(
      setTableAction(
        omitUndefinedProps({
          page: page$,
          pageSize: pageSize$,
        }),
      ),
    );

    dispatch(getDataAction(id));
  };

  const handleEditRow = (rowData) => setEditRowData((prevRowData) => ({ ...prevRowData, ...rowData }));

  const handleUpdateRow = () => {
    dispatch(
      updateContentOwner({
        ...editRowData,
        accountId: id,
      }),
    );
  };

  useEffect(() => {
    handleEditRow({ id: null });
  }, [data]);

  return (
    <div className={styles.Root}>
      <CommonTable
        configHeaders={TABLE_HEADERS}
        configRenderRow={(row) => (
          <Row row={row} editRowData={editRowData} onEditRowData={handleEditRow} onUpdateRow={handleUpdateRow} />
        )}
        data={data || []}
        sortBy={sortBy}
        sortOrder={sortOrder}
        totalCount={totalCount}
        page={page}
        rowsPerPage={pageSize}
        onFilter={handleFilter}
      />
    </div>
  );
}

export default Table;
