import { useEffect, useState } from 'react';
import { User, createUser } from '../../api/Users';
import { useToast } from '../Toast/ToastContext';
import { Form } from 'react-bootstrap';

type AdminFormProps = {
  onClose: () => void;
  onAdminAdded: () => void;
  submit: boolean;
  setSubmit: (value: boolean) => void;
};

export default function NewAdminForm({
  onClose,
  onAdminAdded,
  submit,
  setSubmit,
}: AdminFormProps) {
  const [first, setFirst] = useState('');
  const [last, setLast] = useState('');
  const [email, setEmail] = useState('');
  const [type, setType] = useState('');
  const { addToast } = useToast();
  const [formErrors, setFormErrors] = useState<{
    first?: boolean;
    last?: boolean;
    email?: boolean;
    type?: boolean;
  }>({});

  const handleSubmit = async () => {
    const newUser: User = {
      first_name: first,
      last_name: last,
      email_address: email,
      type: type === 'TA' ? 'ta' : 'instructor',
    };

    if (!emailValid || !first || !last) {
      setValidated(true);
      return;
    }

    try {
      await createUser(newUser);
      if (newUser.type === 'ta') addToast('TA added to roster.', 'success');
      else addToast('Instructor added to roster.', 'success');
      onAdminAdded();
      onClose();
    } catch (error) {
      if (newUser.type === 'ta')
        addToast('Failed to add TA to roster.', 'danger');
      else addToast('Failed to add instructor to roster.', 'danger');
      console.error('Error creating admin:', error);
    }
  };

  const handleFocus = (field: string) => {
    setFormErrors((prevErrors) => ({
      ...prevErrors,
      [field]: false, // Reset error for the specific field
    }));
  };

  const [validated, setValidated] = useState(false);
  const [emailValid, setEmailValid] = useState(false);

  useEffect(() => {
    if (submit) {
      handleSubmit();
      setSubmit(false);
    }
  }, [submit]);

  return (
    <>
      <Form>
        <Form.Group className='mb-3'>
          <Form.Label>First name:</Form.Label>
          <Form.Control
            type='text'
            placeholder={"User's first name..."}
            value={first}
            isValid={validated && Boolean(first.length)}
            isInvalid={validated && !Boolean(first.length)}
            onChange={(e) => setFirst(e.target.value.trim())}
            onFocus={() => handleFocus('first')}
            required
          />
          <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
            type='text'
            placeholder={"User's last name..."}
            value={last}
            isValid={validated && Boolean(last.length)}
            isInvalid={validated && !Boolean(last.length)}
            onChange={(e) => setLast(e.target.value.trim())}
            onFocus={() => handleFocus('last')}
            required
          />
          <Form.Control.Feedback type='invalid'>
            Please enter a last name.
          </Form.Control.Feedback>
        </Form.Group>
        <Form.Group className='mb-3'>
          <Form.Label>Email address:</Form.Label>
          <Form.Control
            required
            type='text'
            placeholder={"User's email address..."}
            value={email}
            isValid={validated && emailValid}
            isInvalid={validated && !emailValid}
            onChange={(event) => {
              setEmail(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>
        <Form.Group>
          <Form.Label>
            User type:
            <br />
            <Form.Text>
              Instructors have broad permission to view/update the roster and
              request/order data. TAs are a passive role with restricted
              permissions.
            </Form.Text>
          </Form.Label>
          <Form.Select
            value={type}
            isValid={validated && Boolean(type.length)}
            isInvalid={validated && !Boolean(type.length)}
            onChange={(e) => setType(e.target.value.trim())}
            onFocus={() => handleFocus('type')}
            required
          >
            <option value='' disabled>
              Select a type...
            </option>
            <option value='Instructor'>Instructor</option>
            <option value='TA'>TA</option>
          </Form.Select>
          <Form.Control.Feedback type='invalid'>
            Please select a user type.
          </Form.Control.Feedback>
        </Form.Group>
      </Form>
    </>
  );
}
