import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { AddRounded, ExpandMoreRounded } from '@mui/icons-material';

import * as selectors from '@/modules/sso/Editor/redux/selectors';
import { setAction } from '@/modules/sso/Editor/redux/slices';

import useLocalPagination from '@/modules/@common/Table/hooks/useLocalPagination';
import AttributesForm from './AttributesForm';
import {
  Button,
  Checkbox,
  Menu,
  MenuItem,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
} from '@/mui/components';

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

function AttributeTable() {
  const dispatch = useDispatch();
  const [showActions, setShowActions] = useState(null);
  const [selected, setSelected] = useState([]);
  const [attributeForm, setAttributeForm] = useState(null);

  const ssoCustomAttributes = useSelector(selectors.ssoCustomAttributesSelector);

  const pagination = useLocalPagination(25, 1);

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

    setSelected(newSelected);
  };

  const handleSelectDeselectAllRows = (checked) => {
    setSelected(checked ? ssoCustomAttributes.map((r) => r.id) : []);
  };

  const handleBulkActivate = () => {
    const payload = ssoCustomAttributes.map((attribute) => ({
      ...attribute,
      status: selected.includes(attribute.id) || attribute.status,
    }));

    dispatch(
      setAction({
        ssoCustomAttributes: payload,
      }),
    );

    setShowActions('');
  };

  const handleBulkDeactivate = () => {
    const payload = ssoCustomAttributes.map((attribute) => ({
      ...attribute,
      status: selected.includes(attribute.id) ? false : attribute.status,
    }));

    dispatch(
      setAction({
        ssoCustomAttributes: payload,
      }),
    );

    setShowActions('');
  };

  const handleBulkDelete = () => {
    const payload = ssoCustomAttributes.filter((attribute) => !selected.includes(attribute.id));

    dispatch(
      setAction({
        ssoCustomAttributes: payload,
      }),
    );

    setShowActions('');
  };

  return (
    <Stack fullWidth>
      <Stack
        spacing={1}
        fullWidth
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        className={styles.Controls}
      >
        <Stack spacing={1} direction="row" alignItems="center">
          <Button
            size="small"
            color="neutral"
            variant="outlined"
            endIcon={<ExpandMoreRounded />}
            disabled={!selected.length}
            onClick={(event) => setShowActions(event.currentTarget)}
          >
            Actions
          </Button>
          {showActions && (
            <Menu open anchorEl={showActions} onClose={() => setShowActions('')}>
              <MenuItem onClick={handleBulkActivate}>Activate</MenuItem>
              <MenuItem onClick={handleBulkDeactivate}>Deactivate</MenuItem>
              <MenuItem onClick={handleBulkDelete}>Delete</MenuItem>
            </Menu>
          )}
        </Stack>
        <Button
          variant="contained"
          size="small"
          color="primary"
          shape="rounded"
          startIcon={<AddRounded />}
          onClick={() => setAttributeForm('new')}
        >
          Add
        </Button>
      </Stack>

      <TableContainer>
        <Table size="medium">
          <TableHead>
            <TableCell padding="checkbox" align="center">
              <Checkbox
                color="primary"
                inputProps={{
                  'aria-label': 'select all desserts',
                }}
                indeterminate={!!selected.length && selected.length < ssoCustomAttributes.length}
                checked={!!ssoCustomAttributes.length && selected.length === ssoCustomAttributes.length}
                onChange={({ target: { checked } }) => {
                  handleSelectDeselectAllRows(checked);
                }}
              />
            </TableCell>
            <TableCell align="left">Name</TableCell>
            <TableCell align="left">Status</TableCell>
          </TableHead>
          <TableBody>
            {ssoCustomAttributes.slice(pagination.startIndex, pagination.endIndex).map((attribute) => {
              const isItemSelected = selected.includes(attribute.id);
              return (
                <TableRow
                  key={attribute.id}
                  hover
                  role="checkbox"
                  aria-checked={isItemSelected}
                  selected={isItemSelected}
                  onClick={() => setAttributeForm(attribute.id)}
                >
                  <TableCell padding="checkbox" align="center">
                    <Checkbox
                      color="primary"
                      checked={isItemSelected}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleSelectDeselectRow(attribute.id);
                      }}
                    />
                  </TableCell>
                  <TableCell>
                    <div>{attribute.name}</div>
                  </TableCell>
                  <TableCell>
                    <div>{attribute.status ? 'Active' : 'Disabled'}</div>
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
        <TablePagination
          component="div"
          rowsPerPageOptions={[5, 10, 25]}
          count={ssoCustomAttributes.length}
          rowsPerPage={pagination.itemsPerPage}
          page={pagination.currentPage}
          onPageChange={(event, page) => {
            pagination.setCurrentPage(page);
          }}
          onRowsPerPageChange={(event) => {
            pagination.setItemsPerPage(+event.target.value);
            pagination.setCurrentPage(1);
          }}
        />
      </TableContainer>
      {attributeForm && <AttributesForm attributeFormId={attributeForm} handleClose={() => setAttributeForm(null)} />}
    </Stack>
  );
}

export default AttributeTable;
