'use client'
import { useEffect, useState, useContext, useRef } from 'react'
import { useMessage } from '@/hooks/useMessage'
import { useAxios } from '@/hooks/useAxios'
import { useRecoilValue } from 'recoil'
import { globalLocaleStore } from '@/store/localeAtom'
import Select from 'react-select'
import { SessionContext } from '@/app/SessionProvider'
import { isEmptyArray, isObjectNotEmpty } from '@/util/common-utils'
import { useEstimateController } from '@/hooks/floorPlan/estimate/useEstimateController'

export default function EstimateCopyPop({ planNo, setEstimateCopyPopupOpen }) {
  const { getMessage } = useMessage()
  const { get } = useAxios()
  const globalLocale = useRecoilValue(globalLocaleStore)
  const { handleEstimateCopy, estimateContextState } = useEstimateController(planNo, true)

  const { session } = useContext(SessionContext)

  // storeLvl 기반 동적 라벨
  const lvl = session?.storeLvl || '1'
  const nextLvl = Number(lvl) + 1
  const saleStoreLabel = globalLocale === 'ko'
    ? `${lvl}차 판매점명 / ID`
    : `${lvl}次販売店名/ID`
  const otherSaleStoreLabel = globalLocale === 'ko'
    ? `${nextLvl}차+하위 판매점명 / ID`
    : `${nextLvl}次下位販売店名/ID`

  const [saleStoreList, setSaleStoreList] = useState([]) // 판매점 리스트
  const [favoriteStoreList, setFavoriteStoreList] = useState([]) //즐겨찾기한 판매점목록
  const [showSaleStoreList, setShowSaleStoreList] = useState([]) //보여줄 판매점목록
  const [otherSaleStoreList, setOtherSaleStoreList] = useState([])
  const [originOtherSaleStoreList, setOriginOtherSaleStoreList] = useState([])

  const [saleStoreId, setSaleStoreId] = useState('') //선택한 상위점
  const [saleStoreName, setSaleStoreName] = useState('') //선택한 상위점명
  const [otherSaleStoreId, setOtherSaleStoreId] = useState('') //선택한 하위점

  const [sendPlanNo, setSendPlanNo] = useState('1')
  const [copyReceiveUser, setCopyReceiveUser] = useState('')

  const ref = useRef() //하위점 자동완성 초기화용

  useEffect(() => {
    let url
    let firstList
    let favList
    let otherList
    if (session.storeId === 'T01') {
      url = `/api/object/saleStore/${session?.storeId}/firstList?userId=${session?.userId}`
    } else {
      if (session.storeLvl === '1') {
        url = `/api/object/saleStore/${session?.storeId}/list?firstFlg=1&userId=${session?.userId}`
      } else {
        // 2차+ 판매점: 자기 자신이 상위점, 하위점 목록 조회
        setSaleStoreId(session?.storeId)
        url = `/api/object/saleStore/${session?.storeId}/childList?storeLvl=${session?.storeLvl}&userId=${session?.userId}`
      }
    }

    get({ url: url }).then((res) => {
      if (!isEmptyArray(res)) {
        res.map((row) => {
          //자동완성 검색을 위한 필드명 셋팅
          row.value = row.saleStoreId
          row.label = row.saleStoreName
        })

        if (session.storeId === 'T01') {
          firstList = res
          //T01을 첫번째로 정렬
          firstList.sort((a, b) => (a.saleStoreId !== 'T01') - (b.saleStoreId !== 'T01') || a.saleStoreId - b.saleStoreId)
          favList = firstList.filter((row) => row.saleStoreId === 'T01' || row.priority !== 'B')

          setSaleStoreList(firstList)
          setFavoriteStoreList(favList)
          setShowSaleStoreList(favList)
          setSaleStoreId(session?.storeId)

          // T01때 디폴트로 T01셋팅하고 하위 2차목록 조회하기 바꾸면(onSelectionChange..) 바꾼거로 2차목록 조회하기
          url = `/api/object/saleStore/${session?.storeId}/list?firstFlg=0&userId=${session?.userId}`
          get({ url: url }).then((res) => {
            if (!isEmptyArray(res)) {
              res.map((row) => {
                row.value = row.saleStoreId
                row.label = row.saleStoreName
              })
              otherList = res
              setOtherSaleStoreList(otherList)
              setOriginOtherSaleStoreList(otherList)
            } else {
              setOtherSaleStoreList([])
            }
          })
        } else {
          if (session.storeLvl === '1') {
            firstList = res
            favList = res.filter((row) => row.priority !== 'B')
            otherList = res.filter((row) => row.firstAgentYn === 'N')
            setSaleStoreList(firstList)
            setFavoriteStoreList(firstList)
            setShowSaleStoreList(firstList)
            setSaleStoreId(firstList[0].saleStoreId)

            setOtherSaleStoreList(otherList)
          } else {
            // 2차+ 판매점: 자기 자신은 상위점명으로, 나머지는 하위점 선택 목록으로 설정
            const myself = res.find((row) => row.saleStoreId === session?.storeId)
            if (myself) {
              setSaleStoreName(myself.saleStoreName)
            }
            otherList = res.filter((row) => row.saleStoreId !== session?.storeId)
            setOtherSaleStoreList(otherList)
            setOriginOtherSaleStoreList(otherList)
          }
        }
      }
    })
  }, [])

  useEffect(() => {
    if (planNo) {
      setSendPlanNo(planNo)
    }
  }, [planNo])

  useEffect(() => {
    if (estimateContextState?.charger) {
      setCopyReceiveUser(session?.userNm)
    }
  }, [estimateContextState?.charger])

  //T01 1차점 자동완성 인풋때 목록 변환
  const onInputChange = (key) => {
    if (key !== '') {
      setShowSaleStoreList(saleStoreList)
    } else {
      setShowSaleStoreList(favoriteStoreList)
    }
  }

  // 상위점 변경 이벤트
  const onSelectionChange = (key) => {
    if (isObjectNotEmpty(key)) {
      if (key.saleStoreId === saleStoreId) {
        return
      }
    }

    if (isObjectNotEmpty(key)) {
      setSaleStoreId(key.saleStoreId)
      const url = `/api/object/saleStore/${key.saleStoreId}/list?firstFlg=0&userId=${session?.userId}`
      let otherList
      get({ url: url }).then((res) => {
        if (!isEmptyArray(res)) {
          res.map((row) => {
            row.value = row.saleStoreId
            row.label = row.saleStoreName
          })

          otherList = res
          setOtherSaleStoreList(otherList)
          setOtherSaleStoreId('')
        } else {
          setOtherSaleStoreId('')
          setOtherSaleStoreList([])
        }
      })
    } else {
      setSaleStoreId('')
      //otherSaleStoreId는 onSelectionChange2에서 초기화됨
      setOtherSaleStoreList(originOtherSaleStoreList)
      handleClear()
    }
  }

  // 하위점 변경 이벤트
  const onSelectionChange2 = (key) => {
    if (isObjectNotEmpty(key)) {
      if (key.saleStoreId === otherSaleStoreId) {
        return
      }
    }

    if (isObjectNotEmpty(key)) {
      setOtherSaleStoreId(key.saleStoreId)
    } else {
      setOtherSaleStoreId('')
    }
  }

  //하위점 자동완성 초기화
  const handleClear = () => {
    if (ref.current) {
      ref.current.clearValue()
    }
  }

  return (
    <div className="modal-popup">
      <div className="modal-dialog">
        <div className="modal-content">
          <div className="modal-header">
            <h1 className="title">{getMessage('estimate.detail.estimateCopyPopup.title')}</h1>
            <button
              type="button"
              className="modal-close"
              onClick={() => {
                setEstimateCopyPopupOpen(false)
              }}
            >
              {getMessage('estimate.detail.estimateCopyPopup.close')}
            </button>
          </div>
          <div className="modal-body">
            <div className="modal-body-inner">
              <div className="explane">{getMessage('estimate.detail.estimateCopyPopup.explane')}</div>
              <div className="estimate-copy-info-wrap">
                <div className="estimate-copy-info-item">
                  <div className="estimate-copy-info-tit">
                    {saleStoreLabel} <span className="red">*</span>
                  </div>
                  {session.storeId === 'T01' && (
                    <div className="estimate-copy-info-box">
                      <div className="estimate-copy-sel">
                        <Select
                          id="long-value-select1"
                          instanceId="long-value-select1"
                          className="react-select-custom"
                          classNamePrefix="custom"
                          placeholder="Select"
                          options={showSaleStoreList}
                          onInputChange={onInputChange}
                          onChange={onSelectionChange}
                          getOptionLabel={(x) => x.saleStoreName}
                          getOptionValue={(x) => x.saleStoreId}
                          isClearable={true}
                          isDisabled={false}
                          value={saleStoreList.filter(function (option) {
                            return option.saleStoreId === saleStoreId
                          })}
                        />
                      </div>
                      <div className="estimate-copy-id">{saleStoreId}</div>
                    </div>
                  )}
                  {session.storeId !== 'T01' && session.storeLvl === '1' && (
                    <div className="estimate-copy-info-box">
                      <div className="estimate-copy-sel">
                        <Select
                          id="long-value-select1"
                          instanceId="long-value-select1"
                          className="react-select-custom"
                          classNamePrefix="custom"
                          placeholder="Select"
                          options={showSaleStoreList[0]}
                          onChange={onSelectionChange}
                          getOptionLabel={(x) => x.saleStoreName}
                          getOptionValue={(x) => x.saleStoreId}
                          isClearable={false}
                          isDisabled={session?.storeLvl !== '1' ? true : session?.storeId !== 'T01' ? true : false}
                          value={showSaleStoreList.filter(function (option) {
                            return option.saleStoreId === saleStoreId
                          })}
                        />
                      </div>
                      <div className="estimate-copy-id">{saleStoreId}</div>
                    </div>
                  )}
                  {session.storeId !== 'T01' && session.storeLvl !== '1' && (
                    <div className="estimate-copy-info-box">
                      <div className="estimate-copy-sel">
                        <input type="text" className="input-light" value={saleStoreName || ''} disabled />
                      </div>
                      <div className="estimate-copy-id">{saleStoreId}</div>
                    </div>
                  )}
                </div>
                <div className="estimate-copy-info-item">
                  <div className="estimate-copy-info-tit">{otherSaleStoreLabel}</div>
                  <div className="estimate-copy-info-box">
                    <div className="estimate-copy-sel">
                      <Select
                        id="long-value-select2"
                        instanceId="long-value-select2"
                        className="react-select-custom"
                        classNamePrefix="custom"
                        placeholder="Select"
                        ref={ref}
                        options={otherSaleStoreList}
                        onChange={onSelectionChange2}
                        getOptionLabel={(x) => x.saleStoreName}
                        getOptionValue={(x) => x.saleStoreId}
                        isClearable={true}
                        isDisabled={otherSaleStoreList.length > 0 ? false : true}
                        value={otherSaleStoreList.filter(function (option) {
                          return option.saleStoreId === otherSaleStoreId
                        })}
                      />
                    </div>
                    <div className="estimate-copy-id">{otherSaleStoreId}</div>
                  </div>
                </div>
                <div className="estimate-copy-info-item">
                  <div className="estimate-copy-info-tit">
                    {getMessage('estimate.detail.estimateCopyPopup.label.receiveUser')} <span className="red">*</span>
                  </div>
                  <div className="input-wrap">
                    <input
                      type="text"
                      className="input-light"
                      required
                      defaultValue={session?.userNm}
                      onChange={(e) => {
                        setCopyReceiveUser(e.target.value)
                      }}
                    />
                  </div>
                </div>
              </div>
            </div>
            <div className="footer-btn-wrap">
              <button
                type="button"
                className="btn-origin navy mr5"
                onClick={() => {
                  handleEstimateCopy(sendPlanNo, copyReceiveUser, saleStoreId, otherSaleStoreId, setEstimateCopyPopupOpen)
                }}
              >
                {getMessage('estimate.detail.estimateCopyPopup.copyBtn')}
              </button>
              <button type="button" className="btn-origin grey" onClick={() => setEstimateCopyPopupOpen(false)}>
                {getMessage('estimate.detail.estimateCopyPopup.close')}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
