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

import { SEARCH_TEXT_MAX_LENGTH } from '../constants';
import { PCN_POST_ONLINE_HELP } from '@/modules/@common/acl/constants';
import { ACCOUNT } from '@/modules/@common/user/constants/rolesType';

import { getConfigHeaders } from '../helpers';
import * as computedState from '../helpers/computedState';
import * as selectors from '../redux/selectors';
import { deleteItemAction, getDataAction, setAction, setTableAction } from '../redux/slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector, getUserRoleTypeSelector } from '@/modules/@common/user/redux/selectors';
import { omitUndefinedProps } from '@/mui/helpers';

import CommonList from '@/modules/@common/List';
import CommonTable, { TableCellActions } from '@/modules/@common/Table';
import Empty from './Empty/Empty';
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  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 selected = useSelector(selectors.selectedSelector);
  const shouldShowEmpty = useSelector(computedState.shouldShowEmpty);

  const userPermissions = useSelector(getUserPermissionsSelector);

  const hasAccount = useSelector(getUserRoleTypeSelector) === ACCOUNT;
  const canCreate = hasPermission(PCN_POST_ONLINE_HELP, userPermissions);

  const [configDelete, setConfirmDelete] = useState(null);

  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());
  };

  const handleSelectDeselectAllRows = (checked) => {
    dispatch(
      setTableAction({
        selected: checked ? data.map((r) => r.id) : [],
      }),
    );
  };

  const handleSelectDeselectRow = (rowId) => {
    const selectedIndex = selected.indexOf(rowId);
    let newSelected = [];

    if (selectedIndex === -1) {
      newSelected = newSelected.concat(selected, rowId);
    } else if (selectedIndex === 0) {
      newSelected = newSelected.concat(selected.slice(1));
    } else if (selectedIndex === selected.length - 1) {
      newSelected = newSelected.concat(selected.slice(0, -1));
    } else if (selectedIndex > 0) {
      newSelected = newSelected.concat(selected.slice(0, selectedIndex), selected.slice(selectedIndex + 1));
    }

    dispatch(
      setTableAction({
        selected: newSelected,
      }),
    );
  };

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

  return (
    <>
      <CommonList
        title="Online Help Configurations"
        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={
          <>
            {canCreate && (
              <Tooltip title="Add Configuration">
                <Button
                  size="small"
                  variant="contained"
                  color="primary"
                  startIcon={<AddRounded />}
                  onClick={() => router.push('/online-help/new')}
                >
                  Configuration
                </Button>
              </Tooltip>
            )}
          </>
        }
      >
        {shouldShowEmpty ? (
          <Empty />
        ) : (
          <CommonTable
            configHeaders={getConfigHeaders(hasAccount)}
            configRenderRow={(row, selectedRows) => {
              const isItemSelected = selectedRows.includes(row.id);

              return (
                <TableRow
                  className={styles.Row}
                  key={row.id}
                  hover
                  role="checkbox"
                  aria-checked={isItemSelected}
                  selected={isItemSelected}
                  onClick={() => router.push(`/online-help/${row.id}`)}
                >
                  <TableCell>
                    <div className={styles.NoWrap}>{row.id}</div>
                  </TableCell>
                  <TableCell>
                    <div className={classNames(styles.Name, styles.NoWrap)}>{row.name}</div>
                  </TableCell>
                  <TableCell>
                    <div className={styles.NoWrap}>{row.suffix}</div>
                  </TableCell>
                  <TableCell>
                    <div className={styles.NoWrap}>{row.helpPageUrl}</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="Delete Configuration" disableInteractive>
                      <IconButton
                        size="small"
                        onClick={(event) => {
                          event.stopPropagation();
                          setConfirmDelete(row.id);
                        }}
                      >
                        <DeleteRounded />
                      </IconButton>
                    </Tooltip>
                  </TableCellActions>
                </TableRow>
              );
            }}
            data={data || []}
            selected={selected}
            sortBy={sortBy}
            sortOrder={sortOrder}
            totalCount={totalCount}
            page={page}
            rowsPerPage={pageSize}
            onSelectDeselectAllRows={handleSelectDeselectAllRows}
            onSelectDeselectRow={handleSelectDeselectRow}
            onFilter={handleFilter}
          />
        )}
      </CommonList>
      {!!configDelete && (
        <Dialog maxWidth="sm" open={!!configDelete} onClose={() => setConfirmDelete(null)}>
          <DialogTitle onClose={() => setConfirmDelete(null)}>Delete</DialogTitle>
          <DialogContent>{`Are you sure you want to delete configuration: ${configDelete}?`}</DialogContent>
          <DialogActions>
            <Button variant="outlined" size="small" color="neutral" onClick={() => setConfirmDelete(null)}>
              Cancel
            </Button>
            <Button
              variant="contained"
              size="small"
              color="error"
              onClick={() => {
                dispatch(deleteItemAction(configDelete));
                setConfirmDelete(null);
              }}
            >
              Delete
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
}

export default List;
