'use client'

import { useEffect, useState } from 'react'
import { useSuitable } from '@/hooks/useSuitable'
import { useSuitableStore } from '@/store/useSuitableStore'
import type { CommCode } from '@/types/CommCode'
import { SUITABLE_HEAD_CODE } from '@/types/Suitable'

export default function SuitableSearch() {
  const [searchValue, setSearchValue] = useState<string>('')

  const { getSuitableCommCode, clearSuitableStore } = useSuitable()
  const { suitableCommCode, searchCategory, setSearchCategory, setSearchKeyword } = useSuitableStore()

  /* 키워드 입력 글자 제한 */
  const handleInputChange = (value: string) => {
    if (Array.from(value).length > 30) {
      alert('検索ワードは最大30文字まで入力できます。')
      setSearchValue(value.slice(0, 30))
      return
    }
    setSearchValue(value)
  }

  /* 키워드 검색 */
  const handleInputSearch = async () => {
    if (!searchValue.trim()) {
      alert('屋根材の製品名を入力してください。')
      return
    }
    setSearchKeyword(searchValue)
  }

  /* 키워드 초기화 */
  const handleInputClear = () => {
    setSearchValue('')
    clearSuitableStore({ items: true, keyword: true })
  }

  useEffect(() => {
    clearSuitableStore({ items: true, category: true, keyword: true })
    getSuitableCommCode()
  }, [])

  return (
    <>
      <div className="sale-form-bx">
        <select className="select-form" name="" id="" value={searchCategory || ''} onChange={(e) => setSearchCategory(e.target.value)}>
          <option value="">屋根材を選択してください.</option>
          {suitableCommCode.get(SUITABLE_HEAD_CODE.ROOF_MATL_GRP_CD)?.map((category: CommCode, index: number) => (
            <option key={index} value={category.code}>
              {category.codeJp}
            </option>
          ))}
        </select>
      </div>
      <div className="sale-form-bx">
        <div className="search-input">
          <input
            type="text"
            className="search-frame"
            placeholder="屋根材 製品名を入力してください."
            value={searchValue}
            onChange={(e) => handleInputChange(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                handleInputSearch()
              }
            }}
          />
          {searchValue && <button className="del-icon" onClick={handleInputClear} />}
          <button className="search-icon" onClick={handleInputSearch} />
        </div>
      </div>
    </>
  )
}
