'use client'

import { useState, useRef, useEffect } from 'react'
import { useAxios } from '@/hooks/useAxios'
import { useMessage } from '@/hooks/useMessage'

export default function UserInfoModal({ userId, userInfoModal, setUserInfoModal }) {
  const { getMessage } = useMessage()

  // api 조회 관련
  const { get, promisePatch, promisePost } = useAxios()
  const [info, setInfo] = useState({
    userId: '',
    name: '',
    nameKana: '',
    category: '',
    tel: '',
    fax: '',
    mail: '',
    groupId: '',
    groupName: '',
  })

  const [password, setPassword] = useState('')
  const [showPwd, setShowPwd] = useState(false)
  const [chkChgPwd, setChkChgPwd] = useState(false)
  const [chgPwd, setChgPwd] = useState('')
  const pwdInput = useRef()
  const chgPwdInput = useRef()

  useEffect(() => {
    async function fetchData() {
      const url = `/api/my-info/my-profile`
      const params = new URLSearchParams({ userId: userId })

      const apiUrl = `${url}?${params.toString()}`

      const resultData = await get({ url: apiUrl })

      if (resultData) {
        setInfo(resultData)
      } else {
        alert(getMessage('common.message.no.data'))
      }
    }

    if (userId) {
      fetchData()
    }
  }, [])

  const pattern = /^[\u0020-\u007E]{1,10}$/

  // 비밀번호 변경
  const handleChangePassword = async () => {
    if (chgPwd === '') {
      chgPwdInput.current.focus()
      return alert(getMessage('myinfo.message.validation.password4'))
    }
    if (password === chgPwd) {
      chgPwdInput.current.focus()
      return alert(getMessage('myinfo.message.validation.password2'))
    }
    if (!pattern.test(chgPwd)) {
      chgPwdInput.current.focus()
      return alert(getMessage('myinfo.message.validation.password3'))
    }

    const params = { loginId: info.userId, chgType: 'C', pwd: password, chgPwd: chgPwd }

    await promisePatch({ url: '/api/login/v1.0/user/change-password', data: params })
      .then((res) => {
        if (res) {
          if (res.data.result.resultCode === 'S') {
            alert(getMessage('myinfo.message.save'))
            setChkChgPwd(false)
            setPassword(chgPwd)
            setChgPwd('')
          } else {
            alert(res.data.result.resultMsg)
          }
        }
      })
      .catch((error) => {
        alert(error.response.data.message)
      })
  }

  // 비밀번호 변경 버튼 클릭 시,
  const checkPasswordProcess = async (e) => {
    if (password === '') {
      pwdInput.current.focus()
      return alert(getMessage('myinfo.message.validation.password1'))
    }

    const param = {
      loginId: userId,
      pwd: password,
    }
    await promisePost({ url: '/api/login/v1.0/login', data: param })
      .then((res) => {
        if (res) {
          if (res.data.result.resultCode === 'S') {
            setChkChgPwd(true)
            setTimeout(() => {
              chgPwdInput.current.focus()
            }, 10)
          } else {
            alert(getMessage('myinfo.message.password.error'))
            setChkChgPwd(false)
            setChgPwd('')
            setTimeout(() => {
              pwdInput.current.focus()
            }, 10)
          }
        }
      })
      .catch((error) => {
        alert(error.response.data.message)
      })
  }

  return (
    <>
      <div className="modal-popup">
        <div className="modal-dialog ">
          <div className="modal-content">
            <div className="modal-header">
              <h1 className="title">{getMessage('myinfo.title')}</h1>
              <button
                type="button"
                className="modal-close"
                onClick={() => {
                  setUserInfoModal(false)
                }}
              >
                {getMessage('myinfo.btn.close')}
              </button>
            </div>
            <div className="modal-body">
              <div className="modal-body-inner">
                <div className="common-table">
                  <table>
                    <colgroup>
                      <col style={{ width: '170px' }} />
                      <col />
                    </colgroup>
                    <tbody>
                      <tr>
                        <th>{getMessage('myinfo.info.userId')}</th>
                        <td>
                          <div className="input-wrap">
                            <input type="text" className="input-light" value={userId || ''} readOnly />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('myinfo.info.nameKana')}</th>
                        <td>
                          <div className="input-wrap">
                            <input type="text" className="input-light" value={info?.nameKana || ''} readOnly />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('myinfo.info.name')}</th>
                        <td>
                          <div className="input-wrap">
                            <input type="text" className="input-light" value={info?.name || ''} readOnly />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('myinfo.info.password')}</th>
                        <td>
                          <div className="form-flex-wrap">
                            <div className="password-input mr10">
                              <input
                                type={`${showPwd ? 'text' : 'password'}`}
                                value={password}
                                ref={pwdInput}
                                onChange={(e) => {
                                  setPassword(e.target.value)
                                }}
                              />
                              <button className={`blink ${showPwd ? 'on' : ''}`} onClick={() => setShowPwd(!showPwd)}></button>
                            </div>
                            <span className="mr10">{getMessage('myinfo.sub.validation.password')}</span>
                            <button
                              className="btn-origin grey mr5"
                              type="button"
                              onClick={(e) => {
                                checkPasswordProcess(e)
                              }}
                            >
                              {getMessage('myinfo.btn.chg.password')}
                            </button>
                          </div>
                        </td>
                      </tr>
                      <tr style={{ display: chkChgPwd ? '' : 'none' }}>
                        <th>
                          {getMessage('myinfo.info.chg.password')} <span className="red">*</span>
                        </th>
                        <td>
                          <div className="form-flex-wrap">
                            <div className="input-wrap mr10" style={{ flex: 1 }}>
                              <input
                                className="input-light"
                                type="text"
                                ref={chgPwdInput}
                                value={chgPwd}
                                onChange={(e) => {
                                  setChgPwd(e.target.value)
                                }}
                              />
                            </div>
                            <button type="button" className="btn-origin grey mr5" onClick={handleChangePassword}>
                              {getMessage('myinfo.btn.chg')}
                            </button>
                            <button
                              type="button"
                              className="btn-origin white "
                              onClick={() => {
                                setChgPwd('')
                                setChkChgPwd(false)
                              }}
                            >
                              {getMessage('myinfo.btn.noChg')}
                            </button>
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('myinfo.info.category')}</th>
                        <td>
                          <div className="input-wrap">
                            <input type="text" className="input-light" value={info?.category || ''} readOnly />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('myinfo.info.tel')}</th>
                        <td>
                          <div className="input-wrap">
                            <input type="text" className="input-light" value={info?.tel || ''} readOnly />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('myinfo.info.fax')}</th>
                        <td>
                          <div className="input-wrap">
                            <input type="text" className="input-light" value={info?.fax || ''} readOnly />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('myinfo.info.mail')}</th>
                        <td>
                          <div className="input-wrap">
                            <input type="text" className="input-light" value={info?.mail || ''} readOnly />
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <div className="footer-btn-wrap">
                <button
                  type="button"
                  className="btn-origin navy "
                  onClick={() => {
                    setUserInfoModal(false)
                  }}
                >
                  {getMessage('myinfo.btn.confirm')}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}
