import { Alert, Button, Form, Modal } from 'react-bootstrap';
import { useMsal } from '@azure/msal-react';
import { Navigate } from 'react-router-dom';
import { loginRequest } from '../auth/AuthConfig';
import { useAuth } from '../auth/AuthProvider';
import { imageDataURIs } from '../ImageExports';
import ContentCard from '../components/shared/ContentCard';
import { Fragment, useEffect, useState } from 'react';
import { createUser, getInstructors } from '../api/Users';
import { useToast } from '../components/Toast/ToastContext';

export const Login = () => {
  const { instance } = useMsal();
  const { user, error } = useAuth();

  const handleLoginRedirect = () => {
    instance
      .loginRedirect({
        ...loginRequest,
        prompt: 'create',
      })
      .catch((error) => console.log(error));
  };

  if (user) {
    return <Navigate to='/' />;
  }

  // First-time setup logic with accompanying modal state
  const [firstTimeSetupModalShown, setFirstTimeSetupModalShown] =
    useState(false);
  useEffect(() => {
    const firstTimeSetupCheck = async () => {
      const instructors = await getInstructors();

      const admin = instructors.find(
        (instructor) => instructor.is_admin === 'true'
      );
      if (!admin) {
        setFirstTimeSetupModalShown(true);
      }
    };

    firstTimeSetupCheck();
  }, []);

  // Very manual form validation state management
  // This is done because enforcing a pattern for @clemson.edu on input type email doesn't work properly
  const [firstTimeSetupFormValidated, setFirstTimeSetupFormValidated] =
    useState(false);
  const [initialAdministratorFirstName, setInitialAdministratorFirstName] =
    useState('');
  const [initialAdministratorLastName, setInitialAdministratorLastName] =
    useState('');
  const [initialAdministratorEmail, setInitialAdministratorEmail] =
    useState('');
  const [emailValid, setEmailValid] = useState(false);

  const { addToast } = useToast();
  // Creates the initial administrator user
  const createInitialAdministrator = async () => {
    // Validate form
    if (
      !emailValid ||
      !initialAdministratorFirstName ||
      !initialAdministratorLastName
    ) {
      setFirstTimeSetupFormValidated(true);
      return;
    }

    try {
      await createUser({
        first_name: initialAdministratorFirstName,
        last_name: initialAdministratorLastName,
        email_address: initialAdministratorEmail,
        type: 'instructor',
        is_admin: 'true',
      });

      setFirstTimeSetupModalShown(false);

      addToast('Administrator user created. You may now log in.', 'success');
    } catch {
      addToast('Failed to create administrator user.', 'danger');
    }
  };

  return (
    <Fragment>
      <Modal show={firstTimeSetupModalShown} backdrop='static'>
        <Form
          onSubmit={(event) => {
            event.preventDefault();
            createInitialAdministrator();
          }}
          noValidate
        >
          <Modal.Header>First-time Application Setup</Modal.Header>
          <Modal.Body>
            <div>
              An administrator user was not found. To use ShipME, an instructor
              user must be created with administrator permissions.
            </div>
            <hr />

            <Form.Group className='mb-3'>
              <Form.Label>First name:</Form.Label>
              <Form.Control
                required
                type='text'
                placeholder={"Administrator's first name..."}
                value={initialAdministratorFirstName}
                isValid={
                  firstTimeSetupFormValidated &&
                  Boolean(initialAdministratorFirstName.length)
                }
                isInvalid={
                  firstTimeSetupFormValidated &&
                  !Boolean(initialAdministratorFirstName.length)
                }
                onChange={(event) => {
                  setInitialAdministratorFirstName(event.target.value.trim());
                }}
              />
              <Form.Control.Feedback type='invalid'>
                Please enter a first name.
              </Form.Control.Feedback>
            </Form.Group>
            <Form.Group className='mb-3'>
              <Form.Label>Last name:</Form.Label>
              <Form.Control
                required
                type='text'
                placeholder={"Administrator's last name..."}
                value={initialAdministratorLastName}
                isValid={
                  firstTimeSetupFormValidated &&
                  Boolean(initialAdministratorLastName.length)
                }
                isInvalid={
                  firstTimeSetupFormValidated &&
                  !Boolean(initialAdministratorLastName.length)
                }
                onChange={(event) => {
                  setInitialAdministratorLastName(event.target.value.trim());
                }}
              />
              <Form.Control.Feedback type='invalid'>
                Please enter a last name.
              </Form.Control.Feedback>
            </Form.Group>
            <Form.Group className='mb-2'>
              <Form.Label>Email address:</Form.Label>
              <Form.Control
                required
                type='text'
                placeholder={"Administrator's email address..."}
                value={initialAdministratorEmail}
                isValid={firstTimeSetupFormValidated && emailValid}
                isInvalid={firstTimeSetupFormValidated && !emailValid}
                onChange={(event) => {
                  setInitialAdministratorEmail(event.target.value.trim());

                  const pattern = /^[a-zA-Z0-9._%+-]+@clemson\.edu$/;
                  if (pattern.test(event.target.value.trim())) {
                    setEmailValid(true);
                  } else {
                    setEmailValid(false);
                  }
                }}
              />
              <Form.Control.Feedback type='invalid'>
                Please enter an email address ending in @clemson.edu.
              </Form.Control.Feedback>
            </Form.Group>
          </Modal.Body>
          <Modal.Footer>
            <Button type='submit' variant='success'>
              Create Administrator
            </Button>
          </Modal.Footer>
        </Form>
      </Modal>

      <div className='d-flex flex-grow-1'>
        <ContentCard fullPage>
          <div
            className='d-flex flex-column justify-content-center align-items-center'
            style={{ minHeight: '100%' }}
          >
            <div>
              {error ? (
                <Alert variant='danger'>
                  <div className='text-center'>
                    <b>Error: </b> {error.message}
                  </div>
                </Alert>
              ) : null}
              <header className='text-center'>
                <h1>Welcome to ShipME!</h1>
                <p className='lead'>
                  ShipME is a custom asset tracking application for use with the
                  ME 4020 capstone course at Clemson University.
                </p>
              </header>
              <hr />
              <div className='d-flex justify-content-center align-items-center'>
                <img
                  src={imageDataURIs.SignInWithMicrosoft}
                  className='img-fluid'
                  style={{ cursor: 'pointer' }}
                  onClick={handleLoginRedirect}
                />
              </div>
            </div>
          </div>
        </ContentCard>
      </div>
    </Fragment>
  );
};
