'use client'

import { useRef, useState } from 'react'
import { useAxios } from '@/hooks/useAxios'
import { useRouter } from 'next/navigation'
import { useMessage } from '@/hooks/useMessage'
import Cookies from 'js-cookie'

import { isObjectNotEmpty, inputTelNumberCheck, inputNumberCheck } from '@/util/common-utils'

import GlobalSpinner from '@/components/common/spinner/GlobalSpinner'

export default function Join() {
  const [isLoading, setIsLoading] = useState(false)

  const { getMessage } = useMessage()
  const { promisePost } = useAxios()
  const router = useRouter()

  const storeQcastNmRef = useRef()
  const storeQcastNmKanaRef = useRef()
  const postCdRef = useRef()
  const addrRef = useRef()
  const telNoRef = useRef()
  const faxRef = useRef()
  const bizNoRef = useRef()
  const userNmRef = useRef()
  const userNmKanaRef = useRef()
  const userIdRef = useRef()
  const emailRef = useRef()
  const userTelNoRef = useRef()
  const userFaxRef = useRef()

  // 가입 신청 유효성 검사
  const joinValidation = (formData) => {

    // 전화번호/FAX 정규식 (일본 형식: 0으로 시작, 하이픈 포함)
    const telRegex = /^0\d{1,4}-\d{1,4}-\d{4}$/


    // 판매대리점 정보 - 판매대리점명
    const storeQcastNm = formData.get('storeQcastNm')
    if (!isObjectNotEmpty(storeQcastNm)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub1.storeQcastNm')]))
      storeQcastNmRef.current.focus()
      return false
    }

    // 판매대리점 정보 - 판매대리점명 후리가나
    const storeQcastNmKana = formData.get('storeQcastNmKana')
    if (!isObjectNotEmpty(storeQcastNmKana)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub1.storeQcastNmKana')]))
      storeQcastNmKanaRef.current.focus()
      return false
    }

    // 판매대리점 정보 - 우편번호
    const postCd = formData.get('postCd')
    if (!isObjectNotEmpty(postCd)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub1.postCd')]))
      postCdRef.current.focus()
      return false
    }

    // 판매대리점 정보 - 주소
    const addr = formData.get('addr')
    if (!isObjectNotEmpty(addr)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub1.addr')]))
      addrRef.current.focus()
      return false
    }


    // 판매대리점 정보 - 전화번호
    const telNo = formData.get('telNo')
    if (!isObjectNotEmpty(telNo)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub1.telNo')]))
      telNoRef.current.focus()
      return false
    } else if (!telRegex.test(telNo)) {
      alert(getMessage('join.validation.check1', [getMessage('join.sub1.telNo')]))
      telNoRef.current.focus()
      return false
    }

    //
    // // 판매대리점 정보 - 전화번호
    // const telNo = formData.get('telNo')
    // if (!isObjectNotEmpty(telNo)) {
    //   alert(getMessage('common.message.required.data', [getMessage('join.sub1.telNo')]))
    //   telNoRef.current.focus()
    //   return false
    // }

    // 판매대리점 정보 - FAX 번호
    const fax = formData.get('fax')
    if (!isObjectNotEmpty(fax)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub1.fax')]))
      faxRef.current.focus()
      return false
    }

    const bizNo = formData.get('bizNo')
    if (!isObjectNotEmpty(bizNo)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub1.bizNo')]))
      bizNoRef.current.focus()
      return false
    }

    // 담당자 정보 - 담당자명
    const userNm = formData.get('userNm')
    if (!isObjectNotEmpty(userNm)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub2.userNm')]))
      userNmRef.current.focus()
      return false
    }

    // 담당자 정보 - 담당자명 후리가나
    const userNmKana = formData.get('userNmKana')
    if (!isObjectNotEmpty(userNmKana)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub2.userNmKana')]))
      userNmKanaRef.current.focus()
      return false
    }

    // 담당자 정보 - 신청 ID
    const userId = formData.get('userId')
    if (!isObjectNotEmpty(userId)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub2.userId')]))
      userIdRef.current.focus()
      return false
    }

    // 담당자 정보 - 이메일 주소
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

    const email = formData.get('email')
    if (!isObjectNotEmpty(email)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub2.email')]))
      emailRef.current.focus()
      return false
    } else {
      // 이메일 정규식 검사
      if (!emailRegex.test(email)) {
        alert(getMessage('join.validation.check1', [getMessage('join.sub2.email')]))
        emailRef.current.focus()
        return false
      }
    }

    // 담당자 정보 - 전화번호
    // const userTelNo = formData.get('userTelNo')
    // if (!isObjectNotEmpty(userTelNo)) {
    //   alert(getMessage('common.message.required.data', [getMessage('join.sub2.telNo')]))
    //   userTelNoRef.current.focus()
    //   return false
    // }


    const userTelNo = formData.get('userTelNo')
    if (!isObjectNotEmpty(userTelNo)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub1.telNo')]))
      userTelNoRef.current.focus()
      return false
    } else if (!telRegex.test(userTelNo)) {
      alert(getMessage('join.validation.check1', [getMessage('join.sub1.telNo')]))
      userTelNoRef.current.focus()
      return false
    }

    // 담당자 정보 - FAX 번호
    const userFax = formData.get('userFax')
    if (!isObjectNotEmpty(userFax)) {
      alert(getMessage('common.message.required.data', [getMessage('join.sub2.fax')]))
      userFaxRef.current.focus()
      return false
    }

    return true
  }



  // 가입 신청
  const joinProcess = async (e) => {
    e.preventDefault()
    const formData = new FormData(e.target)

    if (joinValidation(formData)) {
      if (confirm(getMessage('join.complete.save.confirm'))) {
        const param = {
          storeQcastNm: formData.get('storeQcastNm'),
          storeQcastNmKana: formData.get('storeQcastNmKana'),
          postCd: formData.get('postCd'),
          addr: formData.get('addr'),
          telNo: formData.get('telNo'),
          fax: formData.get('fax'),
          bizNo: formData.get('bizNo'),
          userInfo: {
            userId: formData.get('userId'),
            userNm: formData.get('userNm'),
            userNmKana: formData.get('userNmKana'),
            telNo: formData.get('userTelNo'),
            fax: formData.get('userFax'),
            email: formData.get('email'),
            category: formData.get('category'),
          },
        }

        setIsLoading(true)

        await promisePost({ url: '/api/login/v1.0/user/join', data: param })
          .then((res) => {
            if (res) {
              if (res.data.result.resultCode == 'S') {
                Cookies.set('joinEmail', formData.get('email'), { expires: 1 })
                router.push('/join/complete')
              } else {
                alert(res.data.result.resultMsg)
              }
            }
            setIsLoading(false)
          })
          .catch((error) => {
            setIsLoading(false)
            alert(error.response.data.message)
          })
      }
    }
  }

  return (
    <>
      {isLoading && <GlobalSpinner />}
      <div className="center-page-wrap">
        <div className="center-page-inner">
          <form onSubmit={joinProcess}>
            <div className="center-page-tit">{getMessage('join.title')}</div>
            <div className="sub-table-box signup">
              <div className="table-box-title-wrap">
                <div className="title-wrap">
                  <h3>
                    {getMessage('join.sub1.title')} <span className="important">(*{getMessage('common.require')})</span>
                  </h3>
                  <span className="option">{getMessage('join.sub1.comment')}</span>
                </div>
              </div>
              <div className="common-table">
                <table>
                  <colgroup>
                    <col style={{ width: '180px' }} />
                    <col />
                  </colgroup>
                  <tbody>
                    {/* 판매대리점명 */}
                    <tr>
                      <th>
                        {getMessage('join.sub1.storeQcastNm')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="input-wrap" style={{ width: '700px' }}>
                          <input
                            type="text"
                            id="storeQcastNm"
                            name="storeQcastNm"
                            alt={getMessage('join.sub1.storeQcastNm')}
                            className="input-light"
                            placeholder={getMessage('join.sub1.storeQcastNm_placeholder')}
                            maxLength={30}
                            ref={storeQcastNmRef}
                          />
                        </div>
                      </td>
                    </tr>
                    {/* 판매대리점명 후리가나 */}
                    <tr>
                      <th>
                        {getMessage('join.sub1.storeQcastNmKana')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="input-wrap" style={{ width: '700px' }}>
                          <input
                            type="text"
                            id="storeQcastNmKana"
                            name="storeQcastNmKana"
                            className="input-light"
                            placeholder={getMessage('join.sub1.storeQcastNmKana_placeholder')}
                            maxLength={30}
                            ref={storeQcastNmKanaRef}
                          />
                        </div>
                      </td>
                    </tr>
                    {/* 우편번호/주소 */}
                    <tr>
                      <th>
                        {getMessage('join.sub1.postCd')}/{getMessage('join.sub1.addr')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="flx-box">
                          <div className="input-wrap mr5" style={{ width: '200px' }}>
                            <input
                              type="text"
                              id="postCd"
                              name="postCd"
                              className="input-light"
                              placeholder={getMessage('join.sub1.postCd_placeholder')}
                              onChange={inputNumberCheck}
                              maxLength={7}
                              ref={postCdRef}
                            />
                          </div>
                          <div className="input-wrap" style={{ width: '495px' }}>
                            <input
                              type="text"
                              id="addr"
                              name="addr"
                              className="input-light"
                              placeholder={getMessage('join.sub1.addr_placeholder')}
                              maxLength={50}
                              ref={addrRef}
                            />
                          </div>
                        </div>
                      </td>
                    </tr>
                    {/* 전화번호 */}
                    <tr>
                      <th>
                        {getMessage('join.sub1.telNo')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input
                            type="text"
                            id="telNo"
                            name="telNo"
                            className="input-light"
                            maxLength={15}
                            placeholder={getMessage('join.sub1.telNo_placeholder')}
                            onChange={inputTelNumberCheck}
                            ref={telNoRef}
                          />
                        </div>
                      </td>
                    </tr>
                    {/* FAX 번호 */}
                    <tr>
                      <th>{getMessage('join.sub1.fax')}<span className="important">*</span></th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input type="text" id="fax" name="fax" className="input-light" maxLength={15} onChange={inputNumberCheck} ref={faxRef} />
                        </div>
                      </td>
                    </tr>
                    {/* 법인번호 */}
                    <tr>
                      <th>
                        {getMessage('join.sub1.bizNo')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input
                            type="text"
                            id="bizNo"
                            name="bizNo"
                            className="input-light"
                            maxLength={15}
                            onChange={inputNumberCheck}
                            ref={bizNoRef}
                          />
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <div className="sub-table-box signup">
              <div className="table-box-title-wrap">
                <div className="title-wrap">
                  <h3>
                    {getMessage('join.sub2.title')} <span className="important">(*{getMessage('common.require')})</span>
                  </h3>
                </div>
              </div>
              <div className="common-table">
                <table>
                  <colgroup>
                    <col style={{ width: '180px' }} />
                    <col />
                  </colgroup>
                  <tbody>
                    {/* 담당자명 */}
                    <tr>
                      <th>
                        {getMessage('join.sub2.userNm')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input type="text" id="userNm" name="userNm" className="input-light" maxLength={20} ref={userNmRef} />
                        </div>
                      </td>
                    </tr>
                    {/* 담당자명 후리가나 */}
                    <tr>
                      <th>
                        {getMessage('join.sub2.userNmKana')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input type="text" id="userNmKana" name="userNmKana" maxLength={20} className="input-light" ref={userNmKanaRef} />
                        </div>
                      </td>
                    </tr>
                    {/* 신청 ID */}
                    <tr>
                      <th>
                        {getMessage('join.sub2.userId')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input type="text" id="userId" name="userId" className="input-light" maxLength={20} ref={userIdRef} />
                        </div>
                      </td>
                    </tr>
                    {/* 이메일 주소 */}
                    <tr>
                      <th>
                        {getMessage('join.sub2.email')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input type="text" id="email" name="email" className="input-light" maxLength={50} ref={emailRef} />
                        </div>
                      </td>
                    </tr>
                    {/* 전화번호 */}
                    <tr>
                      <th>
                        {getMessage('join.sub2.telNo')} <span className="important">*</span>
                      </th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input
                            type="text"
                            id="userTelNo"
                            name="userTelNo"
                            className="input-light"
                            maxLength={15}
                            placeholder={getMessage('join.sub1.telNo_placeholder')}
                            onChange={inputTelNumberCheck}
                            ref={userTelNoRef}
                          />
                        </div>
                      </td>
                    </tr>
                    {/* FAX 번호 */}
                    <tr>
                      <th>{getMessage('join.sub2.fax')}<span className="important">*</span></th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input
                            type="text"
                            id="userFax"
                            name="userFax"
                            className="input-light"
                            maxLength={15}
                            onChange={inputNumberCheck}
                            ref={userFaxRef}
                          />
                        </div>
                      </td>
                    </tr>
                    {/* 부서명 */}
                    <tr>
                      <th>{getMessage('join.sub2.category')}</th>
                      <td>
                        <div className="input-wrap" style={{ width: '200px' }}>
                          <input type="text" id="category" name="category" className="input-light" maxLength={20} />
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <div className="sign-up-btn-wrap">
              <button
                type="button"
                className="btn-origin grey mr5"
                onClick={() => {
                  router.push('/login')
                }}
              >
                {getMessage('join.btn.login_page')}
              </button>
              <button type="submit" className="btn-origin navy">
                {getMessage('join.btn.approval_request')}
              </button>
            </div>
          </form>
        </div>
      </div>
    </>
  )
}
