import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import dayjs from 'dayjs';
import timezonePlugin from 'dayjs/plugin/timezone';
import utcPlugin from 'dayjs/plugin/utc';
import { useRouter } from 'next/router';
import { AddRounded, SearchRounded } from '@mui/icons-material';

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

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

import CommonList from '@/modules/@common/List';
import CommonTable from '@/modules/@common/Table';
import Empty from './Empty/Empty';
import { Button, IconButton, InputAdornment, Stack, TableCell, TableRow, TextField, Tooltip } from '@/mui/components';

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

dayjs.extend(utcPlugin);
dayjs.extend(timezonePlugin);
function List() {
  const router = useRouter();

  const dispatch = useDispatch();
  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 search = useSelector(selectors.searchSelector);

  const shouldShowEmpty = useSelector(computedState.shouldShowEmpty);

  const handleFilter = (filter) => {
    const { sortBy: sortBy$, sortOrder: sortOrder$, page: page$, pageSize: pageSize$, ...mainState } = filter;

    dispatch(
      setTableAction(
        omitUndefinedProps({
          sortBy: sortBy$,
          sortOrder: sortOrder$,
          page: page$,
          pageSize: pageSize$,
          selected: [],
        }),
      ),
    );

    dispatch(
      setAction({
        ...mainState,
      }),
    );
    dispatch(getDataAction());
  };

  useEffect(() => {
    dispatch(getDataAction());
  }, []);

  return (
    <CommonList
      title="Advertisers"
      renderFilters={
        <Stack direction="row" alignItems="center" spacing={2}>
          <div>
            <TextField
              className={styles.SearchField}
              size="small"
              placeholder="Search"
              value={search}
              onChange={({ target }) => handleFilter({ search: target.value, page: 1 })}
              inputProps={{
                autoComplete: 'off',
                maxLength: SEARCH_TEXT_MAX_LENGTH,
              }}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={() => null}>
                      <SearchRounded />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
              variant="outlined"
              disabled={shouldShowEmpty}
            />
          </div>
        </Stack>
      }
      renderActions={
        <Tooltip title="Add Advertiser">
          <Button
            size="small"
            variant="contained"
            color="primary"
            startIcon={<AddRounded />}
            onClick={() => router.push('/advertisers/new')}
          >
            Advertiser
          </Button>
        </Tooltip>
      }
    >
      {shouldShowEmpty ? (
        <Empty />
      ) : (
        <CommonTable
          configHeaders={getConfigHeaders()}
          configRenderRow={(row) => (
            <TableRow className={styles.Row} key={row.id} hover onClick={() => router.push(`/advertisers/${row.id}`)}>
              <TableCell>
                <div className={styles.NoWrap}>{row.id}</div>
              </TableCell>
              <TableCell>
                <div className={styles.NoWrap}>{row.name}</div>
              </TableCell>
              <TableCell>
                <div className={styles.NoWrap}>{row.accountName}</div>
              </TableCell>
              <TableCell>
                <div className={styles.NoWrap}>{row.updatedBy}</div>
              </TableCell>
              <TableCell>
                <div className={styles.NoWrap}>{dayjs(row.updatedAt).format('MMM D, YYYY hh:mm A')}</div>
              </TableCell>
            </TableRow>
          )}
          data={data || []}
          sortBy={sortBy}
          sortOrder={sortOrder}
          totalCount={totalCount}
          page={page}
          rowsPerPage={pageSize}
          onFilter={handleFilter}
        />
      )}
    </CommonList>
  );
}

export default List;
