import { useContext } from 'react'
import { useMessage } from '@/hooks/useMessage'
import { useForm } from 'react-hook-form'
import { sessionStore } from '@/store/commonAtom'
import { useRecoilState, useRecoilValue } from 'recoil'
import { useAxios } from '@/hooks/useAxios'
import { globalLocaleStore } from '@/store/localeAtom'
import { login, logout, setSession } from '@/lib/authActions'
import { useSwal } from '@/hooks/useSwal'
import { QcastContext } from '@/app/QcastProvider'
import { useRouter } from 'next/navigation'

export default function ChangePasswordPop(props) {
  const globalLocaleState = useRecoilValue(globalLocaleStore)

  const { setIsGlobalLoading } = useContext(QcastContext)

  const { swalFire } = useSwal()
  const { patch } = useAxios(globalLocaleState)
  const { getMessage } = useMessage()
  const [sessionState, setSessionState] = useRecoilState(sessionStore)
  const router = useRouter()
  const formInitValue = {
    password1: '',
    password2: '',
  }
  const { register, setValue, getValues, handleSubmit, resetField, control, watch } = useForm({
    defaultValues: formInitValue,
  })

  const form = { register, setValue, getValues, handleSubmit, resetField, control, watch }

  //자리수체크 반각 10자리 입력하면 10 리턴
  const checkLength = (pwd1) => {
    let str = new String(pwd1)
    let _byte = 0
    if (str.length !== 0) {
      for (let i = 0; i < str.length; i++) {
        let str2 = str.charAt(i)
        if (encodeURIComponent(str2).length > 4) {
          _byte += 2
        } else {
          _byte++
        }
      }
    }
    return _byte
  }

  //공백제거
  const checkValue = (e) => {
    let spaceChk = /\s/
    if (spaceChk.exec(e.target.value)) {
      e.target.value = e.target.value.replace(/\s|/gi, '')
      return false
    }
  }

  //비밀번호 변경
  const updateProcess = async () => {
    const _password1 = form.watch('password1')
    const _password2 = form.watch('password2')

    //비밀번호 미입력시
    if (_password1.trim() === '') {
      swalFire({
        text: getMessage('main.popup.login.validate3'),
        type: 'alert',
        icon: 'error',
      })
      return false
    }
    if (_password2.trim() === '') {
      swalFire({
        text: getMessage('main.popup.login.validate3'),
        type: 'alert',
        icon: 'error',
      })
      return false
    }

    if (_password1 !== _password2) {
      swalFire({
        text: getMessage('main.popup.login.validate1'),
        type: 'alert',
        icon: 'error',
      })
      return false
    }

    //패스워드 길이수 체크 반각10
    if (checkLength(_password1) > 10) {
      swalFire({
        text: getMessage('main.popup.login.validate2'),
        type: 'alert',
        icon: 'error',
      })
    }

    const param = {
      loginId: sessionState.userId,
      chgType: 'I',
      chgPwd: _password1,
    }

    setIsGlobalLoading(true)
    await patch({ url: '/api/login/v1.0/user/change-password', data: param })
      .then((res) => {
        if (res?.result?.code === 200) {
          setIsGlobalLoading(false)
          if (res?.result?.resultCode === 'S') {
            swalFire({
              text: getMessage('main.popup.login.success'),
              type: 'alert',
              confirmFn: async () => {
                const result = { ...sessionState, pwdInitYn: 'Y' }
                setSession(result)
                setSessionState(result)
                props.setChangePasswordPopOpen(false)
                await login()
              },
            })
          } else {
            swalFire({
              text: getMessage(res?.result?.resultMsg),
              type: 'alert',
              icon: 'error',
            })
          }
        } else {
          setIsGlobalLoading(false)
          logout()
          router.replace('/login', undefined, { shallow: true })
          console.log('code not 200 error')
        }
      })
      .catch((error) => {
        setIsGlobalLoading(false)
        logout()
        router.replace('/login', undefined, { shallow: true })
        console.log('catch::::::::', error)
      })
  }

  return (
    <div className="modal-popup">
      <div className="modal-dialog">
        <div className="modal-content">
          <div className="modal-header">
            <h1 className="title">{getMessage('main.popup.login.popupTitle')}</h1>
          </div>
          <div className="modal-body">
            <div className="modal-body-inner">
              <div className="change-password-box">
                <div className="form-table">
                  <div className="table-item">
                    <div className="table-item-th">
                      <div className="change-password-tit">
                        <div className="tit-b">{getMessage('main.popup.login.newPassword1')}</div>
                        <div className="tit-s">{getMessage('main.popup.login.placeholder')}</div>
                      </div>
                    </div>
                    <div className="table-item-td">
                      <div className="change-password-input">
                        <input
                          type="text"
                          className="change-password"
                          {...form.register('password1')}
                          autoComplete="off"
                          onChange={checkValue}
                          onKeyUp={checkValue}
                          maxLength={10}
                        />
                      </div>
                    </div>
                  </div>
                  <div className="table-item">
                    <div className="table-item-th">
                      <div className="change-password-tit">
                        <div className="tit-b">{getMessage('main.popup.login.newPassword2')}</div>
                        <div className="tit-s">{getMessage('main.popup.login.placeholder')}</div>
                      </div>
                    </div>
                    <div className="table-item-td">
                      <div className="change-password-input">
                        <input
                          type="text"
                          className="change-password"
                          {...form.register('password2')}
                          autoComplete="off"
                          onChange={checkValue}
                          onKeyUp={checkValue}
                          maxLength={10}
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="change-password-guide">
                <span>{getMessage('main.popup.login.guide1')}</span>
                <span>{getMessage('main.popup.login.guide2')}</span>
              </div>
            </div>
            <div className="footer-btn-wrap">
              <button type="sumbit" className="btn-origin navy mr5" onClick={updateProcess}>
                {getMessage('main.popup.login.btn1')}
              </button>
              <button
                type="button"
                className="btn-origin grey"
                onClick={() => {
                  logout()
                  router.replace('/login', undefined, { shallow: true })
                }}
              >
                {getMessage('main.popup.login.btn2')}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
