'use client'

import React, { useEffect, useRef, useState } from 'react'
import { useAxios } from '@/hooks/useAxios'
import { useRecoilState, useRecoilValue, useResetRecoilState } from 'recoil'
import { appMessageStore, globalLocaleStore } from '@/store/localeAtom'
// import Select from 'react-dropdown-select'
import Select from 'react-select'
import KO from '@/locales/ko.json'
import JA from '@/locales/ja.json'
import { stuffSearchState } from '@/store/stuffAtom'
import { isEmptyArray } from '@/util/common-utils'
import dayjs from 'dayjs'
import Link from 'next/link'
import SingleDatePicker from '../common/datepicker/SingleDatePicker'
import { sessionStore } from '@/store/commonAtom'
import { useMessage } from '@/hooks/useMessage'
import { isObjectNotEmpty } from '@/util/common-utils'
export default function StuffSearchCondition() {
  const sessionState = useRecoilValue(sessionStore)
  const [appMessageState, setAppMessageState] = useRecoilState(appMessageStore)
  const globalLocaleState = useRecoilValue(globalLocaleStore)
  const { getMessage } = useMessage()
  const ref = useRef()
  const { get } = useAxios(globalLocaleState)

  //달력 props 관련 날짜 셋팅
  const [startDate, setStartDate] = useState(dayjs(new Date()).add(-1, 'year').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,
  }

  //여기서 선택한 검색조건들을 recoil로 관리
  const resetStuffRecoil = useResetRecoilState(stuffSearchState)
  const [stuffSearch, setStuffSearch] = useRecoilState(stuffSearchState)
  const [objectNo, setObjectNo] = useState('') //물건번호
  const [address, setAddress] = useState('') //물건주소
  const [objectName, setobjectName] = useState('') //물건명
  const [saleStoreName, setSaleStoreName] = useState('') //판매대리점명
  const [receiveUser, setReceiveUser] = useState('') //담당자
  const [dispCompanyName, setDispCompanyName] = useState('') //견적처
  const [dateType, setDateType] = useState('U') //갱신일(U)/등록일(R)
  const [schSelSaleStoreId, setSchSelSaleStoreId] = useState('') //판매대리점 선택

  const [schSelSaleStoreList, setSchSelSaleStoreList] = useState([]) //판매대리점 자동완성 SELECT
  // 조회
  const onSubmit = () => {
    let diff = dayjs(endDate).diff(startDate, 'day')
    if (diff > 366) {
      return alert(getMessage('stuff.message.periodError'))
    }

    setStuffSearch({
      schObjectNo: stuffSearch?.schObjectNo ? stuffSearch.schObjectNo : objectNo,
      schAddress: stuffSearch?.schAddress ? stuffSearch.schAddress : address,
      schObjectName: stuffSearch?.schObjectName ? stuffSearch.schObjectName : objectName,
      schSaleStoreName: stuffSearch?.schSaleStoreName ? stuffSearch.schSaleStoreName : saleStoreName,
      schReceiveUser: stuffSearch?.schReceiveUser ? stuffSearch.schReceiveUser : receiveUser,
      schDispCompanyName: stuffSearch?.schDispCompanyName ? stuffSearch.schDispCompanyName : dispCompanyName,
      schDateType: stuffSearch?.schDateType ? stuffSearch.schDateType : dateType,
      schFromDt: dayjs(startDate).format('YYYY-MM-DD'),
      schToDt: dayjs(endDate).format('YYYY-MM-DD'),
      code: 'E',
      schSelSaleStoreId: stuffSearch?.schSelSaleStoreId ? stuffSearch.schSelSaleStoreId : schSelSaleStoreId,
      startRow: stuffSearch?.startRow ? stuffSearch.startRow : 1,
      endRow: stuffSearch?.endRow ? stuffSearch.endRow : 100,
      schSortType: stuffSearch?.schSortType ? stuffSearch.schSortType : 'R',
    })
  }

  //초기화
  const resetRecoil = () => {
    setObjectNo('')
    setAddress('')
    setobjectName('')
    setSaleStoreName('')
    setReceiveUser('')
    setDispCompanyName('')
    setDateType('U')
    setStartDate(dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'))
    setEndDate(dayjs(new Date()).format('YYYY-MM-DD'))
    setSchSelSaleStoreId('')
    handleClear() //판매대리점선택 자동완성 클리어
    resetStuffRecoil()
  }

  useEffect(() => {
    if (isObjectNotEmpty(sessionState)) {
      // storeId가 T01 이거나 1차점일때만 판매대리점 선택 활성화
      // get({ url: `/api/object/saleStore/TEMP02/list` }).then((res) => {
      get({ url: `/api/object/saleStore/${sessionState?.storeId}/list` }).then((res) => {
        if (!isEmptyArray(res)) {
          res.map((row) => {
            row.value = row.saleStoreId
            row.label = row.saleStoreName
          })
          setSchSelSaleStoreList(res)
        }
      })
    }
  }, [sessionState])

  //초기화 눌렀을 때 자동완성도..
  const handleClear = () => {
    if (ref.current) {
      ref.current.clearValue()
    }
  }

  //판매대리점 자동완성 변경
  const onSelectionChange = (key) => {
    if (isObjectNotEmpty(key)) {
      setSchSelSaleStoreId(key.saleStoreId)
      setStuffSearch({
        ...stuffSearch,
        code: 'S',
        schSelSaleStoreId: key.saleStoreId,
      })
    } else {
      setSchSelSaleStoreId('')
      setStuffSearch({ ...stuffSearch, schSelSaleStoreId: '' })
    }
  }

  useEffect(() => {
    setStartDate(stuffSearch?.schFromDt ? stuffSearch.schFromDt : dayjs(new Date()).add(-1, 'year').format('YYYY-MM-DD'))
    setEndDate(stuffSearch?.schToDt ? stuffSearch.schToDt : dayjs(new Date()).format('YYYY-MM-DD'))
  }, [stuffSearch])

  useEffect(() => {
    if (globalLocaleState === 'ko') {
      setAppMessageState(KO)
    } else {
      setAppMessageState(JA)
    }
  }, [globalLocaleState])

  return (
    <>
      {/* 퍼블적용시작 */}
      <div className="sub-table-box">
        <div className="table-box-title-wrap">
          <div className="title-wrap">
            <h3>{getMessage('stuff.search.title')}</h3>
          </div>
          <div className="left-unit-box">
            <Link href="/management/stuff/tempdetail" scroll={false}>
              <button type="button" className="btn-origin navy mr5">
                {getMessage('stuff.search.btn1')}
              </button>
            </Link>
            <button type="button" className="btn-origin navy mr5" onClick={onSubmit}>
              {getMessage('stuff.search.btn2')}
            </button>
            <button type="button" className="btn-origin grey" onClick={resetRecoil}>
              {getMessage('stuff.search.btn3')}
            </button>
          </div>
        </div>
        <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.search.schObjectNo')}</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      value={stuffSearch?.code === 'E' || stuffSearch?.code === 'M' ? stuffSearch.schObjectNo : objectNo}
                      onChange={(e) => {
                        setObjectNo(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schObjectNo: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>{getMessage('stuff.search.schSaleStoreName')}</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      value={stuffSearch?.schSaleStoreName ? stuffSearch.schSaleStoreName : saleStoreName}
                      onChange={(e) => {
                        setSaleStoreName(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schSaleStoreName: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>{getMessage('stuff.search.schAddress')}</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      value={stuffSearch?.schAddress ? stuffSearch.schAddress : address}
                      onChange={(e) => {
                        setAddress(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schAddress: e.target.value })
                      }}
                    />
                  </div>
                </td>
              </tr>
              <tr>
                <th>{getMessage('stuff.search.schObjectName')}</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      value={stuffSearch?.schObjectName ? stuffSearch.schObjectName : objectName}
                      onChange={(e) => {
                        setobjectName(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schObjectName: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>{getMessage('stuff.search.schDispCompanyName')}</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      value={stuffSearch?.schDispCompanyName ? stuffSearch.schDispCompanyName : dispCompanyName}
                      onChange={(e) => {
                        setDispCompanyName(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schDispCompanyName: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>{getMessage('stuff.search.schSelSaleStoreId')}</th>
                <td>
                  <div className="select-wrap">
                    {schSelSaleStoreList?.length > 0 && (
                      <Select
                        id="long-value-select1"
                        instanceId="long-value-select1"
                        className="react-select-custom"
                        classNamePrefix="custom"
                        placeholder="Select"
                        ref={ref}
                        options={schSelSaleStoreList}
                        onChange={onSelectionChange}
                        getOptionLabel={(x) => x.saleStoreName}
                        getOptionValue={(x) => x.saleStoreId}
                        value={schSelSaleStoreList.filter(function (option) {
                          if (stuffSearch?.code === 'S' && schSelSaleStoreId === '') {
                            return false
                          } else if (stuffSearch?.code === 'S' && schSelSaleStoreId !== '') {
                            return option.saleStoreId === schSelSaleStoreId
                          } else if (stuffSearch?.code === 'E' && schSelSaleStoreId !== '') {
                            return option.saleStoreId === schSelSaleStoreId
                          } else {
                            if (stuffSearch?.schSelSaleStoreId !== '') {
                              return option.saleStoreId === stuffSearch.schSelSaleStoreId
                            } else {
                              return false
                            }
                          }
                        })}
                        isDisabled={sessionState?.storeLvl === '1' ? false : true}
                        isClearable={true}
                      />
                    )}
                  </div>
                </td>
              </tr>
              <tr>
                <th>{getMessage('stuff.search.schReceiveUser')}</th>
                <td>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      value={stuffSearch?.schReceiveUser ? stuffSearch.schReceiveUser : receiveUser}
                      onChange={(e) => {
                        setReceiveUser(e.target.value)
                        setStuffSearch({ ...stuffSearch, code: 'S', schReceiveUser: e.target.value })
                      }}
                    />
                  </div>
                </td>
                <th>{getMessage('stuff.search.period')}</th>
                <td colSpan={3}>
                  <div className="form-flex-wrap">
                    <div className="radio-wrap mr10">
                      <div className="d-check-radio light mr10">
                        <input
                          type="radio"
                          name="radio_ptype"
                          id="radio_u"
                          checked={stuffSearch?.schDateType === 'U' ? true : false}
                          value={'U'}
                          onChange={(e) => {
                            setDateType(e.target.value)
                            setStuffSearch({ ...stuffSearch, code: 'S', schDateType: e.target.value })
                          }}
                        />
                        <label htmlFor="radio_u">{getMessage('stuff.search.schDateTypeU')}</label>
                      </div>
                      <div className="d-check-radio light">
                        <input
                          type="radio"
                          name="radio_ptype"
                          id="radio_r"
                          checked={stuffSearch?.schDateType === 'R' ? true : false}
                          value={'R'}
                          onChange={(e) => {
                            setDateType(e.target.value)
                            setStuffSearch({ ...stuffSearch, code: 'S', schDateType: e.target.value })
                          }}
                        />
                        <label htmlFor="radio_r">{getMessage('stuff.search.schDateTypeR')}</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>
      {/* 퍼블적용끝 */}
    </>
  )
}
