import React, { useEffect, useState } from 'react'
import { Box, Typography, Input, Button, Icon, unityTheme, Grid } from '@ntpkunity/controls'
import { IResetPasswordProps } from './resetPasswordComponent.types'
import { ControlWrap } from './resetPasswordStyle'
import { useForm, Controller } from 'react-hook-form'
import { resetPasswordService, userValidateUrlService } from '../../services/index'
import { validation } from '../../../../shared/helper/methods'

export const ResetPasswordComponent: React.FC<IResetPasswordProps> = ({
  setResponse,
  nextScreenUrl,
  theme,
  validateUrl,
  heading = 'Reset Your Password'

}) => {
  // const [errorMessage, setErrorMessage] = useState('')
  const form: {
    handleSubmit: any
    control: any
    reset: any
    formState: any
    getValues: any
  } = useForm<{ password: '', confirm_password: '' }>()

  const { control, handleSubmit, formState: { errors }, getValues } = form
  const [isValidUrl, setIsValidUrl] = useState(false)
  const [userId, setUserId] = useState(Number)
  const [showPassword, setShowPassword] = useState(false)
  const handlePasswordChange = (): void => {
    setShowPassword(!showPassword)
  }

  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const handleConfirmPasswordChange = (): void => {
    setShowConfirmPassword(!showConfirmPassword)
  }

  useEffect(() => {
    userValidateUrlService(validateUrl).then(res => {
      if (res?.data?.is_valid === true && res?.data?.user_id != null) { setIsValidUrl(true) }
      setUserId(res?.data?.user_id)
    }).catch(error => {
      setResponse({ message: error?.response?.data?.detail, status: error?.response?.status, data: null })
    })
  }, [])

  const onSubmit = (data: any): void => {
    data.resetPasswordScreenUrl = nextScreenUrl
    data.user_id = userId

    resetPasswordService(data).then(res => {
      setResponse({ data: res.data, status: res.status })
    }).catch(error => {
      setResponse({ message: error?.response?.data?.detail, status: error?.response?.status })
    })
  }

  return (
    <ControlWrap theme={unityTheme} className="control-wrap">
      {isValidUrl
        ? (<>
          <Typography theme={unityTheme} variant="h2" component='h2' mb={1}>
            {heading}
          </Typography>
          <Typography theme={unityTheme} className='text-muted' variant='body2' component='span'>
            The password should be 8 to 15 characters long, which must includes uppercase, lowercase, digit and special character.
          </Typography>
          <form onSubmit={(e) => e.preventDefault()}>
            <Box theme={unityTheme} className="scrollable-content" pt={4} mb={4}>
              <Grid container item spacing={3} theme={unityTheme}>
                <Grid theme={unityTheme} item xl={12} sm={12} xs={12}>
                  <Controller
                    name="password"
                    control={control}
                    rules={validation('Password', true, false, true)}
                    render={({ field }) => (
                      <Input
                        theme={unityTheme}
                        fullWidth
                        label='Enter New Password'
                        id="password"
                        type={showPassword ? 'text' : 'password'}
                        endAdornment={
                          <Icon
                            name='IcView'
                            onClick={handlePasswordChange}
                          />
                        }
                        {...field}
                        error={errors?.password?.message}
                      />
                    )} />
                </Grid>
                <Grid theme={unityTheme} item xl={12} sm={12} xs={12}>
                  <Controller
                    name="confirmPassword"
                    control={control}
                    rules={{
                      ...validation('Confirm Password', true),
                      validate: {
                        matchesNewPassword: (value: string | undefined) => {
                          const newPassword = getValues('password')
                          return (
                            newPassword === value || 'Confirm Password does not match'
                          )
                        }
                      }
                    }}
                    render={({ field }) => (
                      <Input
                        theme={unityTheme}
                        fullWidth
                        label='Confirm Password'
                        id="confirmPassword"
                        type={showConfirmPassword ? 'text' : 'password'}
                        {...field}
                        error={errors?.confirmPassword?.message}
                        endAdornment={
                          <Icon
                            name="IcView"
                            onClick={handleConfirmPasswordChange}
                          />
                        }
                      />
                    )}
                  />
                </Grid>
              </Grid>

            </Box>
            <Button type={'submit'} primary text='Save Password' fullWidth theme={unityTheme} onClick={handleSubmit(onSubmit)} />
          </form>
        </>)
        : (null)}

    </ControlWrap>
  )
}

export default ResetPasswordComponent
