import './style.css'

import { Box, CircularProgress, Modal } from '@mui/material'
import axios, { AxiosError } from 'axios'
import { Field, Form, Formik } from 'formik'
import _identity from 'lodash/identity'
import React, { FC, useState } from 'react'
import * as Yup from 'yup'

import { forgotPassword } from '../../api'
import { CustomField } from '../common/CustomField'
import { PoweredBy } from '../common/PoweredBy'

export interface IForgotPasswordProps {
  onClose: () => void;
  onLoginButtonClick: () => void;
  onForgotPasswordSuccess: (res: IAxiosResponseData) => void;
  onForgotPasswordError: (e: AxiosError) => void;
  showPoweredByImage?: boolean;
  displaySuccessMessage?: boolean;
}

interface ValuesTypes {
  email: string;
}

const style: React.CSSProperties = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  minWidth: 480,
  backgroundColor: '#fff',
  border: '1px solid white',
  outline: 'none',
  padding: '14px',
}

const Schema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Required'),
})

export const ForgotPasswordModal: FC<IForgotPasswordProps> = ({
  onClose = _identity,
  onLoginButtonClick = _identity,
  onForgotPasswordSuccess = _identity,
  onForgotPasswordError = _identity,
  showPoweredByImage = false,
  displaySuccessMessage = false,
}) => {
  const [loading, setLoading] = useState(false)
  const [successMessage, setSuccessMessage] = useState<string | null>(null)
  const showSuccess = displaySuccessMessage && successMessage

  const onForgotPassword = async ({ email }: ValuesTypes) => {
    if (showSuccess) {
      setSuccessMessage(null)
      onClose()
      return
    }

    try {
      setLoading(true)
      const { data } = await forgotPassword(email)

      onForgotPasswordSuccess(data)

      if (displaySuccessMessage && data?.success) {
        setSuccessMessage(data?.message)
      }

      if (!displaySuccessMessage) {
        onClose()
      }
    } catch (e) {
      if (axios.isAxiosError(e)) {
        onForgotPasswordError(e)
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <Modal
      open={true}
      onClose={loading ? _identity : onClose}
      aria-labelledby="modal-modal-title"
      aria-describedby="modal-modal-description"
      className="forgot-password-modal"
    >
      <Box style={style}>
        <div>
          <Formik
            initialValues={{ email: '' }}
            validationSchema={Schema}
            onSubmit={onForgotPassword}
          >
            {({ isValid, dirty, handleSubmit }) => (
              <Form onSubmit={handleSubmit}>
                <div className="forgot-password-container">
                  <div className="title">Password Reset</div>
                  <div className="forgot-password-container__singleField">
                    {showSuccess ? (
                      <p id="forgot-password-success-message">{successMessage}</p>
                    ) : (
                      <Field name="email" label="Email" component={CustomField} />
                    )}
                  </div>
                </div>
                <div className="forgot-password-action-button">
                  <button
                    type="submit"
                    disabled={showSuccess ? false : !(isValid && dirty)}
                  >
                    {loading ? (
                      <CircularProgress size="22px" />
                    ) : showSuccess ? (
                      'Close'
                    ) : (
                      'Submit'
                    )}
                  </button>
                </div>
                <div className="login">
                  <span aria-hidden onClick={onLoginButtonClick}>
                    Back to Log In
                  </span>
                </div>
                {showPoweredByImage ? <PoweredBy /> : null}
              </Form>
            )}
          </Formik>
        </div>
      </Box>
    </Modal>
  )
}
