import React, { useState, useRef, useEffect } 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 { useRecoilState, useRecoilValue, useResetRecoilState } from 'recoil'
import FindAddressPopQGrid from './FindAddressPopQGrid'
import { useMessage } from '@/hooks/useMessage'
import { isNotEmptyArray } from '@/util/common-utils'
import SingleDatePicker from '@/components/common/datepicker/SingleDatePicker'
import dayjs from 'dayjs'
import PlanRequestPopQGrid from './PlanRequestPopQGrid'
import { sessionStore } from '@/store/commonAtom'
import { planReqSearchState } from '@/store/planReqAtom'
import { isObjectNotEmpty } from '@/util/common-utils'

import Select from 'react-select'
export default function PlanRequestPop(props) {
  const sessionState = useRecoilValue(sessionStore)

  const globalLocaleState = useRecoilValue(globalLocaleStore)

  const { get } = useAxios(globalLocaleState)

  const { getMessage } = useMessage()
  const ref = useRef()
  // 검색조건 달력 셋팅
  const [startDate, setStartDate] = useState(dayjs(new Date()).add(-3, 'month').format('YYYY-MM-DD'))
  const [endDate, setEndDate] = useState(dayjs(new Date()).format('YYYY-MM-DD'))

  const rangeDatePickerProps1 = {
    startDate, //시작일
    setStartDate,
  }

  const rangeDatePickerProps2 = {
    startDate: endDate, //종료일
    setStartDate: setEndDate,
  }

  const resetPlanReqRecoil = useResetRecoilState(planReqSearchState)

  const [planReqSearch, setPlanReqSearch] = useRecoilState(planReqSearchState)
  const [schPlanReqNo, setSchPlanReqNo] = useState('') //설계의뢰번호
  const [schTitle, setSchTitle] = useState('') //안건명
  const [schAddress, setSchAddress] = useState('') //도도부현
  const [schSaleStoreName, setSchSaleStoreName] = useState('') //판매대리점명
  const [schPlanReqName, setSchPlanReqName] = useState('') //의뢰자명
  const [schPlanStatCd, setSchPlanStatCd] = useState('') //상태코드
  const [schDateGbn, setSchDateGbn] = useState('S') //기간구분코드(S/R)

  //초기화
  const resetRecoil = () => {
    console.log('초기화')
    setSchPlanReqNo('')
    setSchTitle('')
    setSchAddress('')
    setSchSaleStoreName('')
    setSchPlanReqName('')
    setSchDateGbn('S')
    setStartDate(dayjs(new Date()).add(-3, 'month').format('YYYY-MM-DD'))
    setEndDate(dayjs(new Date()).format('YYYY-MM-DD'))
    setSchPlanStatCd('')
    handleClear() //셀렉트 자동완성 초기화
    resetPlanReqRecoil()
  }

  //셀렉트 자동완성 초기화
  const handleClear = () => {
    if (ref.current) {
      ref.current.clearValue()
    }
  }

  // 상태 검색조건 변경
  const onSelectionChange = (key) => {
    //임시작업
    console.log('E::::::::', key)
    if (isObjectNotEmpty(key)) {
      setSchPlanStatCd(key.value)
      setPlanReqSearch({
        ...planReqSearch,
        schPlanStatCd: key.value,
      })
    } else {
      //X누름
      setSchPlanStatCd('')
      setPlanReqSearch({ ...planReqSearch, schPlanStatCd: '' })
    }
  }

  useEffect(() => {
    setStartDate(planReqSearch?.schStartDt ? planReqSearch.schStartDt : dayjs(new Date()).add(-3, 'month').format('YYYY-MM-DD'))
    setEndDate(planReqSearch?.schEndDt ? planReqSearch.schEndDt : dayjs(new Date()).format('YYYY-MM-DD'))
  }, [planReqSearch])

  // 조회
  const onSubmit = () => {
    console.log('조회!!!!', planReqSearch)
  }

  const [gridProps, setGridProps] = useState({
    gridData: [],
    isPageable: false,
    gridColumns: [
      {
        field: 'planStatName',
        headerName: getMessage('stuff.planReqPopup.gridHeader.planStatName'),
        minWidth: 150,
        checkboxSelection: true,
        showDisabledCheckboxes: true,
      },
      {
        field: 'planReqNo',
        headerName: getMessage('stuff.planReqPopup.gridHeader.planReqNo'),
        minWidth: 150,
      },
      {
        field: 'saleStoreId',
        headerName: getMessage('stuff.planReqPopup.gridHeader.saleStoreId'),
        minWidth: 150,
      },
      {
        field: 'saleStoreName',
        headerName: getMessage('stuff.planReqPopup.gridHeader.saleStoreName'),
        minWidth: 150,
      },
      {
        field: 'title',
        headerName: getMessage('stuff.planReqPopup.gridHeader.title'),
        minWidth: 150,
      },
      {
        field: 'address1',
        headerName: getMessage('stuff.planReqPopup.gridHeader.address1'),
        minWidth: 150,
      },
      {
        field: 'houseCntName',
        headerName: getMessage('stuff.planReqPopup.gridHeader.houseCntName'),
        minWidth: 150,
      },
      {
        field: 'planReqName',
        headerName: getMessage('stuff.planReqPopup.gridHeader.planReqName'),
        minWidth: 150,
      },
      {
        field: 'submitDt',
        headerName: getMessage('stuff.planReqPopup.gridHeader.submitDt'),
        minWidth: 150,
      },
    ],
  })

  const tempList = [
    {
      label: '완료',
      value: 'C',
    },
    {
      label: '저장',
      value: 'I',
    },
    {
      label: '접수',
      value: 'R',
    },
    {
      label: '제출',
      value: 'S',
    },
  ]

  return (
    <div className="modal-popup">
      <div className="modal-dialog big">
        <div className="modal-content">
          <div className="modal-header">
            <h1 className="title">{getMessage('stuff.planReqPopup.title')}</h1>
            <button className="modal-close" onClick={() => props.setShowDesignRequestButtonValid(false)}>
              닫기
            </button>
          </div>
          <div className="modal-body">
            <div className="modal-body-inner">
              <div className="design-tit-wrap">
                <h3>{getMessage('stuff.planReqPopup.popTitle')}</h3>
                <div className="design-search-wrap">
                  <button className="btn-origin navy mr5" onClick={onSubmit}>
                    {getMessage('stuff.planReqPopup.btn1')}
                  </button>
                  <button className="btn-origin grey" onClick={resetRecoil}>
                    {getMessage('stuff.planReqPopup.btn2')}
                  </button>
                </div>
              </div>
              <div className="design-request-table">
                <div className="common-table">
                  <table>
                    <colgroup>
                      <col style={{ width: '160px' }} />
                      <col />
                      <col style={{ width: '160px' }} />
                      <col />
                      <col style={{ width: '160px' }} />
                      <col />
                    </colgroup>
                    <tbody>
                      <tr>
                        <th>{getMessage('stuff.planReqPopup.search.planReqNo')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={planReqSearch?.schPlanReqNo ? planReqSearch?.schPlanReqNo : schPlanReqNo}
                              onChange={(e) => {
                                setSchPlanReqNo(e.target.value)
                                setPlanReqSearch({ ...planReqSearch, schPlanReqNo: e.target.value })
                              }}
                            />
                          </div>
                        </td>
                        <th>{getMessage('stuff.planReqPopup.search.title')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={planReqSearch?.schTitle ? planReqSearch?.schTitle : schTitle}
                              onChange={(e) => {
                                setSchTitle(e.target.value)
                                setPlanReqSearch({ ...planReqSearch, schTitle: e.target.value })
                              }}
                            />
                          </div>
                        </td>
                        <th>{getMessage('stuff.planReqPopup.search.address1')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={planReqSearch?.schAddress ? planReqSearch?.schAddress : schAddress}
                              onChange={(e) => {
                                setSchAddress(e.target.value)
                                setPlanReqSearch({ ...planReqSearch, schAddress: e.target.value })
                              }}
                            />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('stuff.planReqPopup.search.saleStoreName')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={planReqSearch?.schSaleStoreName ? planReqSearch?.schSaleStoreName : schSaleStoreName}
                              onChange={(e) => {
                                setSchSaleStoreName(e.target.value)
                                setPlanReqSearch({ ...planReqSearch, schSaleStoreName: e.target.value })
                              }}
                            />
                          </div>
                        </td>
                        <th>{getMessage('stuff.planReqPopup.search.planReqName')}</th>
                        <td>
                          <div className="input-wrap">
                            <input
                              type="text"
                              className="input-light"
                              value={planReqSearch?.schPlanReqName ? planReqSearch?.schPlanReqName : schPlanReqName}
                              onChange={(e) => {
                                setSchPlanReqName(e.target.value)
                                setPlanReqSearch({ ...planReqSearch, schPlanReqName: e.target.value })
                              }}
                            />
                          </div>
                        </td>
                        <th>{getMessage('stuff.planReqPopup.search.planStatName')}</th>
                        <td>
                          <div className="">
                            {/* <select className="select-light" name="" id="" onChange={onSelectionChange}>
                              <option value={''}>All</option>
                              <option value={'C'}>완료</option>
                              <option value={'I'}>저장</option>
                              <option value={'R'}>접수</option>
                              <option value={'S'}>제출</option>
                            </select> */}
                            <Select
                              ref={ref}
                              options={tempList}
                              onChange={onSelectionChange}
                              isSearchable={false}
                              placeholder="선택하세요."
                              isClearable={true}
                            />
                          </div>
                        </td>
                      </tr>
                      <tr>
                        <th>{getMessage('stuff.planReqPopup.search.period')}</th>
                        <td colSpan={5}>
                          <div className="form-flex-wrap">
                            <div className="radio-wrap mr10">
                              <div className="d-check-radio light mr10">
                                <input
                                  type="radio"
                                  name="radio04"
                                  id="ra07"
                                  checked={planReqSearch?.schDateGbn === 'S' ? true : false}
                                  value={'S'}
                                  onChange={(e) => {
                                    setSchDateGbn(e.target.value)
                                    setPlanReqSearch({ ...planReqSearch, schDateGbn: e.target.value })
                                  }}
                                />
                                <label htmlFor="ra07">{getMessage('stuff.planReqPopup.search.schDateGbnS')}</label>
                              </div>
                              <div className="d-check-radio light">
                                <input
                                  type="radio"
                                  name="radio04"
                                  id="ra08"
                                  checked={planReqSearch?.schDateGbn === 'R' ? true : false}
                                  value={'R'}
                                  onChange={(e) => {
                                    setSchDateGbn(e.target.value)
                                    setPlanReqSearch({ ...planReqSearch, schDateGbn: e.target.value })
                                  }}
                                />
                                <label htmlFor="ra08">{getMessage('stuff.planReqPopup.search.schDateGbnR')}</label>
                              </div>
                            </div>
                            <div className="date-picker-wrap">
                              <div className="date-picker" style={{ flex: 1 }}>
                                <SingleDatePicker {...rangeDatePickerProps1} />
                              </div>
                              <span> ~ </span>
                              <div className="date-picker" style={{ flex: 1 }}>
                                <SingleDatePicker {...rangeDatePickerProps2} />
                              </div>
                            </div>
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
              <div className="design-request-grid">
                <div className="design-request-grid-tit">Plan List</div>
                <PlanRequestPopQGrid {...gridProps} />
              </div>
            </div>
            <div className="footer-btn-wrap">
              <button className="btn-origin grey mr5" onClick={() => props.setShowDesignRequestButtonValid(false)}>
                {getMessage('stuff.planReqPopup.btn3')}
              </button>
              <button className="btn-origin navy ">{getMessage('stuff.planReqPopup.btn4')}</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
