import React, { useEffect, useState } from 'react'
import { Box, Typography, Input, Icon, Button, unityTheme, Grid } from '@ntpkunity/controls'
import { ProfileWrap } from './userProfileStyle'
import { useForm, Controller } from 'react-hook-form'
import { validation } from '../../../../shared/helper/methods'
import { IUserProfileProps } from './userProfile.types'
import { userProfileService, userValidateUrlService } from '../../services/index'

export const UserProfileComponent: React.FC<IUserProfileProps> = ({ validateUrl, setResponse }) => {
  const form: {
    handleSubmit: any
    control: any
    reset: any
    formState: any
    getValues: any
  } = useForm<{ first_name: '', last_name: '', password: '', confirm_password: '' }>()
  const { control, handleSubmit, formState: { errors }, getValues, reset } = form

  const [isValidUrl, setIsValidUrl] = useState(false)
  const [userId, setUserId] = useState(null)
  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.user_id = userId
    userProfileService(data).then(res => {
      reset()
      setResponse({ data: res.data, status: res.status, message: res?.message })
    }).catch(error => {
      setResponse({ message: error?.response?.data?.detail, status: error?.response?.status, data: null })
    })
  }

  return (
    <ProfileWrap theme={unityTheme} className="control-wrap">
      {isValidUrl
        ? (<>
        <Typography theme={unityTheme} variant="h2" component='h2' mb={4}>
        {"Let's Create  Your"}  <span className='text-primary'>Account</span>
        </Typography>
        <form onSubmit={(e) => e.preventDefault()}>
          <Box theme={unityTheme} className="scrollable-content">
            <Grid container item spacing={3} theme={unityTheme}>
              <Grid theme={unityTheme} item xl={6} sm={6} xs={12}>
                <Controller
                  name="first_name"
                  control={control}
                  rules={{
                    ...validation('First Name', true),
                    validate: {
                      nameLenght: (value: string) => {
                        return (
                          value?.length <= 50 || 'First Name length should not be greater than 50 characters.'
                        )
                      }
                    }
                  }}
                  render={({ field: { onChange, value } }) => (
                    <Input
                      theme={unityTheme}
                      fullWidth type={'text'}
                      label='First Name'
                      id="first_name"
                      onChange={onChange}
                      value={value}
                      error={errors?.first_name?.message}
                    />
                  )} />
              </Grid>
              <Grid theme={unityTheme} item xl={6} sm={6} xs={12}>
                <Controller
                  name="last_name"
                  control={control}
                  rules={{
                    validate: {
                      nameLenght: (value: string) => {
                        return (
                          value?.length <= 50 || 'First Name length should not be greater than 50 characters.'
                        )
                      }
                    }
                  }}
                  render={({ field: { onChange, value } }) => (
                    <Input
                      theme={unityTheme}
                      fullWidth type={'Last Name'}
                      label='Last Name (Optional)'
                      id="last_name"
                      onChange={onChange}
                      value={value}
                      error={errors?.last_name?.message}
                    />
                  )} />
              </Grid>
              <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='Create 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>

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

  )
}
export default UserProfileComponent
