import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
import { Fragment, useEffect, useState } from 'react';
import {
  getInstructors,
  getUsers,
  Instructor,
  updateInstructor,
  User,
} from '../../api/Users';
import { Form } from 'react-bootstrap';
import { useAuth } from '../../auth/AuthProvider';
import { useToast } from '../Toast/ToastContext';
import { Link } from 'react-router-dom';

interface TransferOwnershipModalProps {
  show: boolean;
  handleClose: () => void;
  setTransferInitiated: (status: boolean) => void; // allows Settings page to know transfer status
}

// Modal which handles the beginning of the administrator/owner transfer process
// Made specifically to follow existing modals for the Settings page
const TransferOwnershipModal: React.FC<TransferOwnershipModalProps> = ({
  show,
  handleClose,
  setTransferInitiated,
}) => {
  // Hooks
  const currentUser = useAuth().user;
  const { addToast } = useToast();

  // Retrieve all the instructors (both subtype and parent) and assemble a list
  const [instructors, setInstructors] = useState<Instructor[] | null>(null);
  const [instructorUsers, setInstructorUsers] = useState<User[] | null>(null);
  const [currentTransferInstructor, setCurrentTransferInstructor] = useState<
    Instructor | undefined
  >();
  useEffect(() => {
    const retrieveInstructors = async () => {
      const instructors = await getInstructors();
      setInstructors(
        // Exclude current user
        instructors.filter(
          (instructor) => instructor.user_id !== currentUser?.user_id
        )
      );
      // Determines whether there is a transfer already in progress
      setCurrentTransferInstructor(
        instructors.find((instructor) => instructor.is_admin === 'incoming')
      );

      const instructorUsers = await getUsers('instructor');
      setInstructorUsers(
        // Exclude current user
        instructorUsers.filter((user) => user.user_id !== currentUser?.user_id)
      );
    };

    retrieveInstructors();
  }, [currentUser]); // currentUser must be populated for this to work

  // Maintain state of user input for instructor to transfer to
  const [selectedInstructor, setSelectedInstructor] = useState<number>();
  // Handles the first stage of the transfer process (selecting a candidate)
  const transferOwnership = async () => {
    const response = await updateInstructor(selectedInstructor as number, {
      is_admin: 'incoming',
    });

    if (response.is_admin === 'incoming') {
      // Transfer is now in progress
      setCurrentTransferInstructor(response);
      setTransferInitiated(true);

      // Replace the instructor object with response
      setInstructors(
        (instructors as Instructor[]).map((instructor) =>
          instructor.instructor_id === selectedInstructor
            ? response
            : instructor
        )
      );

      addToast('Ownership transfer initiated.', 'success');
    } else {
      addToast('Failed to initiate ownership transfer.', 'danger');
    }

    hideModal();
  };
  const cancelTransfer = async () => {
    const response = await updateInstructor(
      currentTransferInstructor?.instructor_id as number,
      {
        is_admin: 'false',
      }
    );

    if (response.is_admin === 'false') {
      // Transfer is now cancelled
      setCurrentTransferInstructor(undefined);
      setTransferInitiated(false);

      // Replace the instructor object with response
      setInstructors(
        (instructors as Instructor[]).map((instructor) =>
          instructor.instructor_id === selectedInstructor
            ? response
            : instructor
        )
      );

      addToast('Ownership transfer cancelled.', 'success');
    } else {
      addToast('Failed to cancel ownership transfer.', 'danger');
    }

    hideModal();
  };

  const hideModal = () => {
    setSelectedInstructor(undefined);
    handleClose();
  };

  return (
    <Modal show={show} onHide={hideModal}>
      <Modal.Header closeButton>Transfer Application Ownership</Modal.Header>
      <Modal.Body>
        {currentTransferInstructor ? (
          // Allows instructor to cancel transfer process
          <Fragment>
            <div className='mb-3'>
              An ownership transfer to the user with the email address{' '}
              <b>
                {
                  instructorUsers?.find(
                    (user) => user.user_id === currentTransferInstructor.user_id
                  )?.email_address
                }
              </b>{' '}
              has already been initiated.
            </div>
            <div>
              You must cancel the pending transfer before transferring to
              another instructor.
            </div>
          </Fragment>
        ) : (
          // Allows instructor to initiate transfer process
          <Fragment>
            <div>
              <span className='text-danger'>
                <b>Warning:</b> this action is potentially irreversible.
              </span>{' '}
              The transfer process is completed the next time the selected user
              logs in. Until then, you will be able to cancel the transfer.
            </div>
            <hr />
            {instructors?.length ? (
              <Fragment>
                <div className='mb-2'>
                  Select an existing instructor to transfer ownership of the
                  ShipME application to:
                </div>
                <div className='mb-2'>
                  <Form.Select
                    defaultValue={0}
                    value={selectedInstructor as number}
                    onChange={(event) =>
                      setSelectedInstructor(Number(event.target.value))
                    }
                  >
                    <option value={0} disabled>
                      Select an instructor...
                    </option>
                    {instructors?.map((instructor) => {
                      const matchedInstructorUser = instructorUsers?.find(
                        (user) => user.user_id === instructor.user_id
                      );

                      return (
                        <option
                          key={instructor.instructor_id}
                          value={instructor.instructor_id}
                        >
                          {matchedInstructorUser?.first_name +
                            ' ' +
                            matchedInstructorUser?.last_name +
                            ', ' +
                            matchedInstructorUser?.email_address}
                        </option>
                      );
                    })}
                  </Form.Select>
                </div>
              </Fragment>
            ) : (
              <div className='mb-2'>
                There are no instructors to transfer ownership to.{' '}
                <Link to='/roster'>Add an instructor on the Roster page.</Link>
              </div>
            )}
          </Fragment>
        )}
      </Modal.Body>
      <Modal.Footer>
        <Button variant='secondary' onClick={hideModal}>
          Cancel
        </Button>
        <Button
          variant='danger'
          onClick={
            currentTransferInstructor ? cancelTransfer : transferOwnership
          }
          disabled={!selectedInstructor && !currentTransferInstructor}
        >
          {currentTransferInstructor ? 'Cancel Transfer' : 'Transfer Ownership'}
        </Button>
      </Modal.Footer>
    </Modal>
  );
};

export default TransferOwnershipModal;
