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

import {
  ACTIONS_OPTIONS,
  ACTIONS_SHOW_PLAYERS,
  SEARCH_TEXT_MAX_LENGTH,
  STATUSES_ALL,
  STATUSES_OPTIONS,
} from '../constants';
import { PCN_POST_PUBLISHER } from '@/modules/@common/acl/constants';
import { ACCOUNT } from '@/modules/@common/user/constants/rolesType';

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

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

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

// in current implementation phase table multi actions is disable
const TABLE_MULTIACTIONS_ENABLED = false;

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

  const selected = useSelector(selectors.selectedSelector);

  const shouldShowEmpty = useSelector(computedState.shouldShowEmpty);

  const userPermissions = useSelector(getUserPermissionsSelector);

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

  const accountIdFromUrl = router.query?.accountId;
  const accountAutocompleteValue =
    accountIdFromUrl && account?.value && !account?.label && data?.length
      ? { value: accountIdFromUrl, label: data[0].accountName }
      : account;

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

  const handleAction = (action) => {
    if (action === ACTIONS_SHOW_PLAYERS) {
      // console.log(selected);
    }
  };

  useEffect(() => {
    if (accountIdFromUrl) {
      dispatch(
        setAction({
          account: { value: +accountIdFromUrl, label: '' },
        }),
      );
    }
    dispatch(getDataAction());
  }, []);

  return (
    <CommonList
      title="Hubs"
      renderFilters={
        <Stack direction="row" alignItems="center" spacing={2}>
          {TABLE_MULTIACTIONS_ENABLED && !hasAccount && (
            <Select
              className={styles.ActionsSelect}
              size="small"
              variant="outlined"
              disabled={!selected.length}
              displayEmpty
              renderValue={() => 'Actions'}
              onChange={({ target: { value } }) => handleAction(value)}
            >
              {ACTIONS_OPTIONS.map((option) => (
                <MenuItem value={option.value} key={option.value}>
                  {option.label}
                </MenuItem>
              ))}
            </Select>
          )}

          <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>

          {!hasAccount && (
            <Stack spacing={1} direction="row" alignItems="center">
              <Divider orientation="vertical" flexItem />
              <FilterAltRounded color="shades.900" fontSize="medium" />
            </Stack>
          )}

          {!hasAccount && (
            <Autocomplete
              className={styles.AccountSelect}
              value={accountAutocompleteValue}
              options={accountOptions || []}
              loading={!accountOptions}
              size="small"
              onChange={(e, selectedAccount) => handleFilter({ account: selectedAccount, page: 1 })}
              onOpen={() => {
                dispatch(getAccountOptionsAction(''));
              }}
              onInputChange={(e, searchText) => dispatch(getAccountOptionsAction(searchText))}
              renderInput={(params) => <TextField {...params} value="" variant="outlined" placeholder="Account" />}
            />
          )}

          {!hasAccount && (
            <Autocomplete
              className={styles.StatusSelect}
              value={STATUSES_OPTIONS.find((s) => s.value === status) ?? STATUSES_ALL}
              options={STATUSES_OPTIONS}
              size="small"
              onChange={(e, selected$) => handleFilter({ status: selected$?.value ?? STATUSES_ALL, page: 1 })}
              renderInput={(params) => <TextField {...params} placeholder="Status" />}
            />
          )}
        </Stack>
      }
      renderActions={
        <Stack direction="row">
          {canCreate && (
            <Tooltip title="Add Hub">
              <Button
                size="small"
                variant="contained"
                color="primary"
                startIcon={<AddRounded />}
                onClick={() => router.push('/hubs/new')}
              >
                Hub
              </Button>
            </Tooltip>
          )}
        </Stack>
      }
    >
      {shouldShowEmpty ? (
        <Empty />
      ) : (
        <CommonTable
          configHeaders={getConfigHeaders(hasAccount)}
          enableBulkActions={TABLE_MULTIACTIONS_ENABLED && !hasAccount}
          configRenderRow={(row, selectedRows, onSelectDeselectRow) => {
            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(`/hubs/${row.id}`)}
              >
                {TABLE_MULTIACTIONS_ENABLED && !hasAccount && (
                  <TableCell padding="checkbox" align="center">
                    <Checkbox color="primary" checked={isItemSelected} onClick={() => onSelectDeselectRow(row.id)} />
                  </TableCell>
                )}
                <TableCell>{row.id}</TableCell>
                <TableCell>
                  <div className={styles.NoWrap}>{row.name}</div>
                </TableCell>
                {!hasAccount && (
                  <TableCell>
                    <div className={styles.NoWrap}>{row.accountName}</div>
                  </TableCell>
                )}
                <TableCell>
                  <div className={styles.NoWrap}>{row.players.length ? row.players.length : '0'}</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 || []}
          selected={selected}
          sortBy={sortBy}
          sortOrder={sortOrder}
          totalCount={totalCount}
          page={page}
          rowsPerPage={pageSize}
          onSelectDeselectAllRows={handleSelectDeselectAllRows}
          onSelectDeselectRow={handleSelectDeselectRow}
          onFilter={handleFilter}
        />
      )}
    </CommonList>
  );
}

export default List;
