import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
import { Fragment, useEffect, useState } from 'react';
import { removeStaleUsers } from '../../utils/ImportRosterHelper';
import { OverlayTrigger, Table, Tooltip } from 'react-bootstrap';

interface ImportRosterModalProps {
  show: boolean;
  handleClose: () => void;
  title: string;
  staleUsers: any[];
  onPrimaryAction: () => void;
}

const ImportRosterModal: React.FC<ImportRosterModalProps> = ({
  show,
  handleClose,
  title,
  staleUsers,
  onPrimaryAction,
}) => {
  const [usersToRemove, setUsersToRemove] = useState<number[]>([]);

  const handleCheck = (user_id: number) => {
    setUsersToRemove((prev) => {
      if (prev.includes(user_id)) {
        return prev.filter((id) => id !== user_id);
      } else {
        return [...prev, user_id];
      }
    });
  };

  const handleCloseImportHere = () => {
    setUsersToRemove([]);
  };

  const [indeterminate, setIndeterminate] = useState(false);
  const [allSelected, setAllSelected] = useState(false);
  useEffect(() => {
    if (
      staleUsers
        .filter((user) => user.can_be_deleted)
        .some((user) => usersToRemove.includes(user.user_id)) &&
      !staleUsers
        .filter((user) => user.can_be_deleted)
        .every((user) => usersToRemove.includes(user.user_id))
    ) {
      setIndeterminate(true);
    } else {
      setIndeterminate(false);
    }

    if (
      staleUsers
        .filter((user) => user.can_be_deleted)
        .every((user) => usersToRemove.includes(user.user_id))
    ) {
      setAllSelected(true);
    } else {
      setAllSelected(false);
    }
  }, [usersToRemove]);

  return (
    <Modal
      show={show}
      onHide={() => {
        handleCloseImportHere();
        handleClose();
      }}
    >
      <Modal.Header closeButton>
        <Modal.Title>{title}</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <div className={`${staleUsers.length ? 'mb-3' : ''}`}>
          Please confirm that you would like to import the provided roster.
        </div>
        {staleUsers.length > 0 && (
          <Fragment>
            <hr />
            <div>
              <div className='mb-3'>
                The following{' '}
                <OverlayTrigger
                  placement='top'
                  overlay={
                    <Tooltip>
                      Only students that aren't tied to requests can be removed
                      during import.
                    </Tooltip>
                  }
                >
                  <span style={{ borderBottom: '1px dotted black' }}>
                    students with no requests
                  </span>
                </OverlayTrigger>{' '}
                are not listed in the provided roster. If you'd like to remove
                them, you can do so by checking the boxes beside their names.
              </div>
            </div>
            <Table bordered size='sm' responsive className='mb-2'>
              <thead>
                <tr>
                  <th>
                    <div className='d-flex justify-content-center align-items-center'>
                      <input
                        type='checkbox'
                        className='form-check mb-0'
                        checked={allSelected}
                        ref={(element) => {
                          if (element) {
                            element.indeterminate = indeterminate;
                          }
                        }}
                        onChange={() => {
                          if (allSelected) {
                            staleUsers
                              .filter((user) => user.can_be_deleted)
                              .forEach((user) => {
                                if (usersToRemove.includes(user.user_id)) {
                                  handleCheck(user.user_id);
                                }
                              });
                          } else {
                            staleUsers
                              .filter((user) => user.can_be_deleted)
                              .forEach((user) => {
                                if (!usersToRemove.includes(user.user_id)) {
                                  handleCheck(user.user_id);
                                }
                              });
                          }
                        }}
                      />
                    </div>
                  </th>
                  <th>Student Name</th>
                  <th>Section #</th>
                  <th>Team #</th>
                </tr>
              </thead>
              <tbody>
                {staleUsers
                  .filter((user) => user.can_be_deleted)
                  .map((user) => (
                    <tr key={user.user_id}>
                      <td>
                        <div className='d-flex justify-content-center align-items-center'>
                          <input
                            type='checkbox'
                            className='form-check'
                            checked={usersToRemove.includes(user.user_id)}
                            onChange={() => handleCheck(user.user_id)}
                          />
                        </div>
                      </td>
                      <td>{user.name}</td>
                      <td>{user.section_id}</td>
                      <td>{user.team_num}</td>
                    </tr>
                  ))}
              </tbody>
            </Table>
          </Fragment>
        )}
      </Modal.Body>
      <Modal.Footer>
        <Button
          variant='secondary'
          onClick={() => {
            handleCloseImportHere();
            handleClose();
          }}
        >
          Cancel
        </Button>
        <Button
          variant='primary'
          onClick={() => {
            onPrimaryAction();
            removeStaleUsers(usersToRemove);
          }}
        >
          Import Roster
        </Button>
      </Modal.Footer>
    </Modal>
  );
};

export default ImportRosterModal;
