import React, { useEffect, useState, useRef } from 'react'
import { useForm } from 'react-hook-form'
import { queryStringFormatter } from '@/util/common-utils'
import { useAxios } from '@/hooks/useAxios'
import { globalLocaleStore } from '@/store/localeAtom'
import { useRecoilValue } from 'recoil'
import FindAddressPopQGrid from './FindAddressPopQGrid'
import { useMessage } from '@/hooks/useMessage'

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

  const { get } = useAxios(globalLocaleState)

  const { getMessage } = useMessage()

  const [prefId, setPrefId] = useState('')
  const [address1, setAddress1] = useState('')
  const [address2, setAddress2] = useState('')
  const [address3, setAddress3] = useState('')
  const gridRef = useRef()

  const [gridProps, setGridProps] = useState({
    gridData: [],
    isPageable: false,
    gridColumns: [],
  })
  const formInitValue = {
    zipNo: '',
  }
  const { register, setValue, getValues, handleSubmit, resetField, control, watch } = useForm({
    defaultValues: formInitValue,
  })

  const form = { register, setValue, getValues, handleSubmit, resetField, control, watch }
  //우편번호 검색
  const searchPostNum = () => {
    //   //7830060
    //   //9302226
    //   //0790177 3개짜리
    console.log(watch('zipNo'))
    const params = {
      zipcode: watch('zipNo'),
    }

    get({ url: `https://zipcloud.ibsnet.co.jp/api/search?${queryStringFormatter(params)}` }).then((res) => {
      console.log('우편조회 API결과:::::', res)
      if (res.status === 200) {
      } else {
        alert('등록된 우편번호에서 주소를 찾을 수 없습니다. 다시 입력해주세요.')
      }
    })
  }
  // 주소적용 클릭
  const zipInfo = () => {
    console.log('주소적용 클릭:::::::::')
    // setAddress3('3333')
    // setAddress3('4444')
    // setAddress3('5555')
    props.zipInfo({
      zipNo: '3434343',
      address1: '3333',
      address2: '4444',
      address3: '5555',
    })

    props.setShowButtonValid(false)
  }

  //숫자만
  const handleKeyUp = (e) => {
    let input = e.target
    input.value = input.value.replace(/[^0-9]/g, '')
  }
  return (
    <div className="modal-popup">
      <div className="modal-dialog middle">
        <div className="modal-content">
          <div className="modal-header">
            <h1 className="title">{getMessage('stuff.addressPopup.title')}</h1>
            <button className="modal-close" onClick={() => props.setShowButtonValid(false)}>
              닫기
            </button>
          </div>
          <div className="modal-body">
            <div className="modal-body-inner">
              <div className="address-input-wrap">
                <input
                  type="text"
                  className="address-input"
                  maxLength={7}
                  onKeyUp={handleKeyUp}
                  {...form.register('zipNo')}
                  placeholder={getMessage('stuff.addressPopup.placeholder')}
                />
                <button className="search-btn" onClick={searchPostNum}></button>
              </div>
              <div className="address-grid">
                <FindAddressPopQGrid {...gridProps} gridRef={gridRef} />
              </div>
            </div>
            <div className="footer-btn-wrap">
              <button className="btn-origin grey mr5" onClick={() => props.setShowButtonValid(false)}>
                {getMessage('stuff.addressPopup.btn1')}
              </button>
              <button className="btn-origin navy " onClick={zipInfo}>
                {getMessage('stuff.addressPopup.btn2')}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
