import React, { useState } 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'
import { isNotEmptyArray } from '@/util/common-utils'
export default function FindAddressPop(props) {
  const globalLocaleState = useRecoilValue(globalLocaleStore)

  const { get } = useAxios(globalLocaleState)

  const { getMessage } = useMessage()

  const [prefId, setPrefId] = useState(null)
  const [zipNo, setZipNo] = useState(null)
  const [address1, setAddress1] = useState(null)
  const [address2, setAddress2] = useState(null)
  const [address3, setAddress3] = useState(null)

  const [gridProps, setGridProps] = useState({
    gridData: [],
    isPageable: false,
    gridColumns: [
      {
        field: 'address1',
        headerName: getMessage('stuff.addressPopup.gridHeader.address1'),
        minWidth: 150,
        checkboxSelection: true,
        showDisabledCheckboxes: true,
      },
      {
        field: 'address2',
        headerName: getMessage('stuff.addressPopup.gridHeader.address2'),
        minWidth: 150,
      },
      {
        field: 'address3',
        headerName: getMessage('stuff.addressPopup.gridHeader.address3'),
        minWidth: 150,
      },
    ],
  })

  //검색필드
  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개짜리
    const params = {
      zipcode: watch('zipNo'),
    }

    get({ url: `https://zipcloud.ibsnet.co.jp/api/search?${queryStringFormatter(params)}` }).then((res) => {
      if (res.status === 200) {
        if (isNotEmptyArray(res.results)) {
          setGridProps({ ...gridProps, gridData: res.results })
        } else {
          alert(getMessage('stuff.addressPopup.error.message1'))
          setGridProps({ ...gridProps, gridData: [] })
        }
      } else {
        alert(getMessage('stuff.addressPopup.error.message1'))
        setGridProps({ ...gridProps, gridData: [] })
      }
    })
  }
  // 주소적용 클릭
  const applyAddress = () => {
    if (prefId == null) {
      alert(getMessage('stuff.addressPopup.error.message2'))
    } else {
      props.zipInfo({
        zipNo: zipNo,
        address1: address1,
        address2: address2,
        address3: address3,
        prefId: prefId,
      })

      //팝업닫기
      props.setShowAddressButtonValid(false)
    }
  }

  //숫자만
  const handleKeyUp = (e) => {
    let input = e.target
    input.value = input.value.replace(/[^0-9]/g, '')

    if (e.key === 'Enter') {
      searchPostNum()
    }
  }

  //그리드에서 선택한 우편정보
  const getSelectedRowdata = (data) => {
    if (isNotEmptyArray(data)) {
      setAddress1(data[0].address1)
      setAddress2(data[0].address2)
      setAddress3(data[0].address3)
      setPrefId(data[0].prefcode)
      setZipNo(data[0].zipcode)
    } else {
      setAddress1(null)
      setAddress2(null)
      setAddress3(null)
      setPrefId(null)
      setZipNo(null)
    }
  }

  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.setShowAddressButtonValid(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} getSelectedRowdata={getSelectedRowdata} />
              </div>
            </div>
            <div className="footer-btn-wrap">
              <button className="btn-origin grey mr5" onClick={() => props.setShowAddressButtonValid(false)}>
                {getMessage('stuff.addressPopup.btn1')}
              </button>
              <button className="btn-origin navy " onClick={applyAddress}>
                {getMessage('stuff.addressPopup.btn2')}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
