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'
import { useSwal } from '@/hooks/useSwal'
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 { swalFire } = useSwal()
  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 = () => {
    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 {
          swalFire({ text: getMessage('stuff.addressPopup.error.message1'), type: 'alert', icon: 'warning' })
          setGridProps({ ...gridProps, gridData: [] })
        }
      } else {
        swalFire({ text: getMessage('stuff.addressPopup.error.message1'), type: 'alert', icon: 'warning' })
        setGridProps({ ...gridProps, gridData: [] })
      }
    })
  }
  // 주소적용 클릭
  const applyAddress = () => {
    if (prefId == null) {
      swalFire({ text: getMessage('stuff.addressPopup.error.message2'), type: 'alert', icon: 'warning' })
    } 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)
    }
  }

  //그리드 더블클릭
  const getCellDoubleClicked = (event) => {
    setAddress1(event.data.address1)
    setAddress2(event.data.address2)
    setAddress3(event.data.address3)
    setPrefId(event.data.prefcode)
    setZipNo(event.data.zipcode)

    if (event.data.prefcode == null) {
      return swalFire({ text: getMessage('stuff.addressPopup.error.message2'), type: 'alert', icon: 'warning' })
    } else {
      props.zipInfo({
        zipNo: event.data.zipcode,
        address1: event.data.address1,
        address2: event.data.address2,
        address3: event.data.address3,
        prefId: event.data.prefcode,
      })
    }
    props.setShowAddressButtonValid(false)
  }

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