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

import { SEARCH_TEXT_MAX_LENGTH, STATUSES_ALL, STATUSES_OPTIONS, STATUSES_REVOKED } from '../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 { getAccountOptionsAction, getDataAction, revokeAction, setAction, setTableAction } from '../redux/slices';
import { 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 CopyTooltip from './CopyTooltip/CopyTooltip';
import Empty from './Empty/Empty';
import {
  Autocomplete,
  Button,
  Checkbox,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Divider,
  IconButton,
  InputAdornment,
  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 [invokeId, setInvokeId] = useState(null);

  const hasAccount = useSelector(getUserRoleTypeSelector) === ACCOUNT;

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

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

  return (
    <>
      <CommonList
        title="Guest invitations"
        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={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" />}
            />
            {!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" />}
              />
            )}
          </Stack>
        }
        renderActions={null}
      >
        {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}
                >
                  {TABLE_MULTIACTIONS_ENABLED && !hasAccount && (
                    <TableCell padding="checkbox" align="center">
                      <Checkbox color="primary" checked={isItemSelected} onClick={() => onSelectDeselectRow(row.id)} />
                    </TableCell>
                  )}

                  <TableCell>
                    <CopyTooltip title={row.email}>
                      <div className={styles.Email}>{row.email}</div>
                    </CopyTooltip>
                  </TableCell>
                  {!hasAccount && (
                    <TableCell>
                      <CopyTooltip title={row.accountName}>
                        <div className={styles.NoWrap}>{row.accountName}</div>
                      </CopyTooltip>
                    </TableCell>
                  )}
                  <TableCell>
                    <CopyTooltip title={row.invitedByFullName}>
                      <div className={styles.NoWrap}>{row.invitedByFullName}</div>
                    </CopyTooltip>
                  </TableCell>
                  <TableCell>
                    <CopyTooltip title={row.videoData?.videoId ?? ''}>
                      <div className={styles.NoWrap}>{row.videoData?.videoName}</div>
                    </CopyTooltip>
                  </TableCell>
                  <TableCell>
                    <div className={styles.NoWrap}>{dayjs(row.createdAt).format('MMM D, YYYY hh:mm A')}</div>
                  </TableCell>
                  <TableCell>
                    <div className={styles.NoWrap}>{dayjs(row.updatedAt).format('MMM D, YYYY hh:mm A')}</div>
                  </TableCell>
                  <TableCell>
                    <div className={styles.NoWrap}>{row.invStatus}</div>
                  </TableCell>
                  <TableCellActions>
                    {row.invStatus !== STATUSES_REVOKED && (
                      <Tooltip title="Revoke invitation" disableInteractive>
                        <IconButton size="small" onClick={() => setInvokeId(row.id)}>
                          <CloseRounded />
                        </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>
      {invokeId && (
        <Dialog maxWidth="sm" open={invokeId} onClose={() => setInvokeId('')}>
          <DialogTitle onClose={() => setInvokeId('')}>Revoke Invitation</DialogTitle>
          <DialogContent>Are you sure you want to revoke the Invitations?</DialogContent>
          <DialogActions>
            <Button variant="outlined" size="small" color="neutral" onClick={() => setInvokeId('')}>
              Cancel
            </Button>
            <Button
              variant="contained"
              size="small"
              color="error"
              onClick={() => {
                dispatch(revokeAction(invokeId));
                setInvokeId('');
              }}
            >
              Revoke
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </>
  );
}

export default List;
