import React, {
  FC,
  MouseEvent,
  useState,
  useEffect
} from 'react'

import axios from 'axios'

import Alert from '../alert'

import Form, {
  FormEmailField,
  FormPhoneField,
  FormReadOnlyField,
  FormTextField,
  FormTextAreaField
} from '../form'

import { LaunchModal } from '../modal'

import { sendFormDataToPymail } from '../../apis/pymail'

type SpecificContactFormProps = {
  blurId?: string,
  person?: string,
  infoat?: boolean,
  [other:string]: unknown
}

const SpecificContactForm: FC<SpecificContactFormProps> = ({
  blurId,
  person="BSCS Science Learning",
  infoat=false,
  ...other
}: SpecificContactFormProps) => {
  if (!person && !infoat) {
    infoat = true
  }
  
  const [firstnameValid, setFirstNameValid] = useState(false)
  const [firstnameValue, setFirstNameValue] = useState("")
  const [lastnameValid, setLastNameValid] = useState(false)
  const [lastnameValue, setLastNameValue] = useState("")
  const [emailValid, setEmailValid] = useState(false)
  const [emailValue, setEmailValue] = useState("")
  const [phoneValid, setPhoneValid] = useState(true)
  const [phoneValue, setPhoneValue] = useState("")
  const [messageValid, setMessageValid] = useState(false)
  const [messageValue, setMessageValue] = useState("")

  const [loading, setLoading] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [errorMessage, setErrorMessage] = useState("")

  const [valid, setValid] = useState(false)
  
  const cancelToken = axios.CancelToken.source()

  const handleFail = (errorMessage: string): void => {
    setLoading(false)
    setSubmitted(true)
    setErrorMessage(errorMessage)
  }

  const handleSuccess = (): void => {
    setLoading(false)
    setSubmitted(true)
  }

  const handleSubmit = (e: MouseEvent): void => {
    e.preventDefault()
    
    setLoading(true)

    let page
    if (typeof window !== `undefined`) {
      page = window.location.href
    }

    const data = {
      "firstname": firstnameValue,
      "lastname": lastnameValue,
      "email": emailValue,
      "phone": phoneValue,
      "message": messageValue,

      "page": page,
      "sendto": infoat ? "INFOAT" : person,
      "form_name": "SpecificContactForm",
      "functions": []
    }

    sendFormDataToPymail({
      cancelToken: cancelToken,
      data: data,
      successCallback: handleSuccess,
      failCallback: handleFail
    })
  }


  useEffect(() => {
    if (firstnameValid && lastnameValid && phoneValid && emailValid && messageValid) {
      setValid(true)
      return
    }
    
    setValid(false)
  }, [firstnameValid, lastnameValid, phoneValid, emailValid, messageValid])

  useEffect(() => {
    return () => cancelToken.cancel()
  // eslint-disable-next-line
  }, [])

  return (
    <LaunchModal
      blurId={blurId}
      button={true}
      launchText={`Contact ${person}`}
      modalId="specific-contact-form-modal"
      title={`Contact ${person}`}
      {...other}
    >
      {!loading && submitted && !errorMessage &&
        <Alert variant="green">Message sent.</Alert>
      }
      {!loading && submitted && errorMessage &&
        <Alert variant="red">{errorMessage}</Alert>
      }
      <Form
        className="w-full flex flex-wrap mb-3"
        loading={loading}
        valid={valid}
        submitted={submitted}
        submitCallback={(e: MouseEvent) => handleSubmit(e)}
      >
        <div className="w-full">
          <FormReadOnlyField
            label="To"
            name="To"
            placeholder={person}
          />
        </div>
        <div className="w-full">
          <FormTextField
            className=""
            id="first"
            label="First Name"
            name="First Name"
            setValid={(valid) => setFirstNameValid(valid)}
            setValue={(value) => setFirstNameValue(value)}
          />
        </div>
        <div className="w-full">
          <FormTextField
            className=""
            id="last"
            label="Last Name"
            name="Last Name"
            setValid={(valid) => setLastNameValid(valid)}
            setValue={(value) => setLastNameValue(value)}
          />
        </div>
        <div className="w-full">
          <FormEmailField
            className=""
            id="email"
            invalidMessage="Email is invalid."
            label="Email"
            name="Email"
            setValid={(valid) => setEmailValid(valid)}
            setValue={(value) => setEmailValue(value)}
          />
        </div>
        <div className="w-full">
          <FormPhoneField
            className=""
            id="phone"
            label="Phone"
            name="Phone"
            optional={true}
            setValid={(valid) => setPhoneValid(valid)}
            setValue={(value) => setPhoneValue(value)}
          />
        </div>
        <div className="w-full">
          <FormTextAreaField
            className=""
            id="message"
            label="Message"
            name="Message"
            setValid={(valid) => setMessageValid(valid)}
            setValue={(value) => setMessageValue(value)}
          />
        </div>
      </Form>
    </LaunchModal>
  )
}

export default SpecificContactForm
