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, ContentCopyRounded, FilterAltRounded, SearchRounded } from '@mui/icons-material';

import { SEARCH_TEXT_MAX_LENGTH, TYPE_ALL, TYPE_OPTIONS } from '../constants';

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

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

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

dayjs.extend(utcPlugin);
dayjs.extend(timezonePlugin);

const getAccountTypeName = (accountType) => TYPE_OPTIONS.find((o) => o.value === accountType)?.label;

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 type = useSelector(selectors.typeSelector);
  const account = useSelector(selectors.accountSelector);
  const accountOptions = useSelector(selectors.accountOptionsSelector);

  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$,
        }),
      ),
    );

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

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

  return (
    <CommonList
      title="Roles"
      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 spacing={1} direction="row" alignItems="center">
            <Divider orientation="vertical" flexItem />
            <FilterAltRounded color="shades.900" fontSize="medium" />
          </Stack>
          <Autocomplete
            className={styles.StatusSelect}
            value={TYPE_OPTIONS.find((s) => s.value === type) ?? TYPE_ALL}
            options={TYPE_OPTIONS}
            size="small"
            onChange={(e, selected$) => handleFilter({ type: selected$?.value ?? TYPE_ALL, page: 1 })}
            renderInput={(params) => <TextField {...params} placeholder="Type" />}
          />
          <Autocomplete
            className={styles.HubSelect}
            value={account}
            options={accountOptions || []}
            optionLabelKey="name"
            optionValueKey="id"
            loading={!accountOptions}
            size="small"
            onOpen={() => dispatch(getAccountOptionsAction(''))}
            onChange={(e, selectedAccount) => handleFilter({ account: selectedAccount, page: 1 })}
            onInputChange={(e, searchText) => dispatch(getAccountOptionsAction(searchText))}
            renderInput={(params) => <TextField {...params} placeholder="Account" />}
          />
        </Stack>
      }
      renderActions={
        <Tooltip title="Add Role">
          <Button
            size="small"
            variant="contained"
            color="primary"
            startIcon={<AddRounded />}
            onClick={() => router.push('/roles-permissions/new')}
          >
            Role
          </Button>
        </Tooltip>
      }
    >
      {shouldShowEmpty ? (
        <Empty />
      ) : (
        <CommonTable
          configHeaders={getConfigHeaders()}
          configRenderRow={(row) => (
            <TableRow
              className={styles.Row}
              key={row.id}
              hover
              role="checkbox"
              onClick={() => router.push(`/roles-permissions/${row.id}`)}
            >
              <TableCell>
                <div className={styles.NoWrap}>{row.id}</div>
              </TableCell>
              <TableCell>
                <div className={styles.NoWrap}>{row.displayName}</div>
              </TableCell>
              <TableCell>
                <div className={styles.NoWrap}>{getAccountTypeName(row.type)}</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>
              <TableCellActions>
                <Tooltip title="Duplicate" disableInteractive>
                  <IconButton
                    size="small"
                    onClick={(e) => {
                      e.stopPropagation();
                      router.push(`/roles-permissions/${row.id}/duplicate`);
                    }}
                  >
                    <ContentCopyRounded />
                  </IconButton>
                </Tooltip>
              </TableCellActions>
            </TableRow>
          )}
          data={data || []}
          sortBy={sortBy}
          sortOrder={sortOrder}
          totalCount={totalCount}
          page={page}
          rowsPerPage={pageSize}
          onFilter={handleFilter}
        />
      )}
    </CommonList>
  );
}

export default List;
