import './style.css'

import { CircularProgress } 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 { resetPassword } from '../../api'
import { CustomField } from '../common/CustomField'

interface IResetPasswordProps {
  token?: string;
  onResetPasswordSuccess?: (res: any) => void;
  onResetPasswordError?: (e: AxiosError) => void;
}

const Schema = Yup.object().shape({
  password: Yup.string()
    .min(8, 'Password must have 8+ characters')
    .required('Required')
    .matches(
      new RegExp('^(?=.*[@$!%*#?&])'),
      'Password must contain at least one special character'
    ),
  password_confirmation: Yup.string()
    .required('Required')
    .oneOf([Yup.ref('password'), null], 'Passwords must match'),
})

export const ResetPasswordContainer: FC<IResetPasswordProps> = ({
  token: tokenProps = '',
  onResetPasswordSuccess = _identity,
  onResetPasswordError = _identity,
}) => {
  const [loading, setLoading] = useState(false)
  return (
    <div className="reset-password">
      <div className="title">Change Password</div>
      <Formik
        initialValues={{ password: '', password_confirmation: '' }}
        validationSchema={Schema}
        onSubmit={async (values: any) => {
          try {
            setLoading(true)
            let token
            if (tokenProps) {
              token = tokenProps
            } else {
              if (typeof window !== 'undefined') {
                const params: URLSearchParams = new URL(`${window.location}`).searchParams
                token = params.get('token')
              }
            }

            const payload = {
              token,
              ...values,
            }
            const res = await resetPassword(payload)
            onResetPasswordSuccess(res)
          } catch (e) {
            if (axios.isAxiosError(e)) {
              onResetPasswordError(e)
            }
          } finally {
            setLoading(false)
          }
        }}
      >
        {({ isValid, dirty }) => (
          <Form>
            <div className="body">
              <div className="field-item">
                <Field
                  name="password"
                  label="New Password"
                  type="password"
                  component={CustomField}
                />
              </div>
              <div className="field-item">
                <Field
                  name="password_confirmation"
                  label="Confirm Password"
                  type="password"
                  component={CustomField}
                />
              </div>
            </div>
            <div className="action-button">
              <button type="submit" disabled={!(isValid && dirty)}>
                {loading ? <CircularProgress size="22px" /> : 'Submit'}
              </button>
            </div>
          </Form>
        )}
      </Formik>
    </div>
  )
}
