'use client'

import { searchState } from '@/store/boardAtom'
import { useRecoilState, useRecoilValue } from 'recoil'
import { useState } from 'react'
import { useMessage } from '@/hooks/useMessage'
import QnaRegModal from '@/components/community/modal/QnaRegModal'

export default function Search({ title = '', subTitle = '', isSelectUse = false, clsCode = '' }) {
  const { getMessage } = useMessage()
  const [open, setOpen] = useState(false)
  const search = useRecoilValue(searchState)
  const [searchForm, setSearchForm] = useRecoilState(searchState)

  const [selectPageBlock, setSelectPageBlock] = useState(search.pageBlock)
  const [searchValue, setSearchValue] = useState(search.searchValue)
  const [searchView, setSearchView] = useState(search.searchValue ? true : false)
  const [searchViewText, setSearchViewText] = useState(search.searchValue ? search.searchValue : '')

  // Enter 키 처리
  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      handleSubmit(e)
    }
  }

  // 조회 값 처리
  const handleSearch = (text, block) => {
    if (text !== '') {
      setSearchView(true)
      setSearchViewText(text)
      setSearchForm({ ...searchForm, currentPage: 1, searchValue: text, pageBlock: block, searchFlag: true })
    } else {
      setSearchView(false)
      setSearchViewText('')
      setSearchForm({
        ...searchForm,
        currentPage: 1,
        searchValue: '',
        pageBlock  : block,
        searchFlag : !searchForm.searchFlag,
      })
    }
    // 조회 후 값 비워주기
    setSearchValue('')
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    handleSearch(searchValue, selectPageBlock)
  }

  return (
    <>
      <div className="community-search-warp">
        <div className="community-search-box">
          <input
            type="text"
            className="community-input"
            placeholder={getMessage('board.sub.search.placeholder')}
            onChange={(e) => {
              setSearchValue(e.target.value)
            }}
            onKeyDown={handleKeyDown}
            value={searchValue}
          />

          <button type="button" className="community-search-ico"
                  onClick={() => handleSearch(searchValue, selectPageBlock)}></button>

        </div>
        {searchView && (
          <div className="community-search-keyword">
            {isSelectUse ? (
              <>
                <div
                  dangerouslySetInnerHTML={{
                    __html: getMessage('board.sub.search.result', [`<span>${searchViewText}</span>`, `<span>${search.totalCount}</span>`]),
                  }}
                ></div>
              </>
            ) : (
              <>
                <div
                  dangerouslySetInnerHTML={{
                    __html: getMessage('board.sub.search.archive.result', [`<span>${searchViewText}</span>`, `<span>${search.totalCount}</span>`]),
                  }}
                ></div>
              </>
            )}
          </div>
        )}
      </div>
      <div className="table-box-title-wrap">
        <div className="title-wrap">
          <h3>{subTitle}</h3>
          <ul className="info-wrap">
            <li>
              {getMessage('board.sub.total')} <span className="red">{search.totalCount}</span>
            </li>
          </ul>
        </div>
        {isSelectUse && (
          <div className="left-unit-box">
            {clsCode === 'QNA' &&
              <div>
                <button className="btn-origin navy mr10"
                        onClick={() => {
                          setOpen(true)
                        }}> {getMessage('qna.sub.btn.inquiry')}</button>
              </div>
            }
            <div className="select-box" style={{ width: '80px' }}>
              <select
                className="select-light black"
                value={selectPageBlock}
                onChange={(e) => {
                  setSelectPageBlock(Number(e.target.value))
                  const text = searchValue ? searchValue : searchViewText
                  handleSearch(text, Number(e.target.value))
                }}
              >
                <option value={100}>100</option>
                <option value={200}>200</option>
                <option value={300}>300</option>
                <option value={400}>400</option>
                <option value={500}>500</option>
              </select>
            </div>
          </div>
        )}
      </div>
      {open && <QnaRegModal setOpen={setOpen} setReload={handleSearch} searchValue={searchValue ? searchValue : searchViewText} selectPageBlock = {selectPageBlock}/>}
    </>
  )
}
